Python strings cheat sheet 🧵
Slicing, searching, changing case, splitting, joining and cleaning text. Every snippet runs in your browser, and the page prints on one sheet.
Make and combine
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
print("=" * 12)
print(len(full))+ joins strings, * repeats them, len() counts characters.
Index and slice
word = "Python"
print(word[0], word[-1])
print(word[0:3])
print(word[2:])
print(word[::-1])Positions start at 0. [start:stop] stops before stop. [::-1] reverses.
Change case
s = "hello World"
print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())Strings never change in place: each method returns a new string.
Clean up
raw = " Yes please! \n"
print(repr(raw.strip()))
print("---hi---".strip("-"))
print("a,b,,c".replace(",,", ","))strip() removes spaces and newlines from both ends.
Search
s = "the cat sat on the mat"
print("cat" in s)
print(s.find("sat"))
print(s.count("the"))
print(s.startswith("the"), s.endswith("mat"))find() gives -1 when the text is missing.
Split and join
line = "apples,pears,plums"
fruit = line.split(",")
print(fruit)
print(" and ".join(fruit))
print("one two three".split())split() with no argument splits on any run of spaces.
Check what is inside
print("42".isdigit(), "4.2".isdigit())
print("abc".isalpha(), "abc1".isalnum())
print(" ".isspace())Handy for checking input before converting it.