Python String Cheatsheet for Leetcode
String Basics
- Create string: s = "hello"
- Access characters: s[0], s[-1]
- Length: len(s)
- Loop: for ch in s:
- Compare: s1 == s2
- Substring: s[1:4]
- Concatenate: s1 + s2
- Repeat: s * 3
- Check substring: "lo" in s
- Replace: s.replace("a", "b")
- Remove whitespace: s.strip(), s.lstrip(), s.rstrip()
- Upper/lower: s.upper(), s.lower()
String to List and Back
- Split by space: s.split()
- Split by character: s.split(',')
- Join list into string: " ".join(list)
- String to list of characters: list(s)
- List of characters to string: "".join(char_list)
Reversing Strings
- Reverse entire string: s[::-1]
- Reverse word order: " ".join(s.split()[::-1])
- Reverse each word: " ".join(w[::-1] for w in s.split())
- Reverse string with loop:
reversed_s = ''
for ch in s:
reversed_s = ch + reversed_s
String Search & Manipulation
- Find: s.find("a") returns index or -1
- rfind: s.rfind("a")
- Count occurrences: s.count("a")
- Starts/Ends with: s.startswith("yo"), s.endswith("is")
Python String Cheatsheet for Leetcode
- isalpha(), isdigit(), isalnum(), isspace()
Leetcode Patterns (Strings)
- Reverse Words in a String: " ".join(s.split()[::-1])
- Valid Palindrome: s == s[::-1]
- Longest Common Prefix: vertical scan of characters
- Anagram check:
sorted(s1) == sorted(s2)
OR Counter(s1) == Counter(s2)
- Two-pointer technique (palindrome or compare ends):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]: return False
left += 1
right -= 1
String Formatting
- f-strings: name = "Alice"; f"Hello {name}"
- .format(): "Hi {}".format(name)
- % formatting: "Hi %s" % name
Regex (Regular Expressions)
import re
- Search: re.search(pattern, string)
- Match: re.match(pattern, string)
- Find all: re.findall(pattern, string)
- Replace: re.sub(pattern, repl, string)