Home | Scratch | Java
Python String Methods Cheat Sheet
Basic Information
len(s): Returns the length of strings.len("hello") # Output: 5
Case Conversion
s.lower(): Converts all characters insto lowercase."Hello".lower() # Output: "hello"s.upper(): Converts all characters insto uppercase."Hello".upper() # Output: "HELLO"s.capitalize(): Capitalizes the first letter ins."hello".capitalize() # Output: "Hello"s.title(): Capitalizes the first letter of each word ins."hello world".title() # Output: "Hello World"
Searching and Checking
s.find(sub): Returns the index of the first occurrence ofsubins(or-1if not found)."hello".find("e") # Output: 1s.count(sub): Counts the occurrences ofsubins."banana".count("a") # Output: 3s.startswith(prefix): Checks ifsstarts withprefix."hello".startswith("he") # Output: Trues.endswith(suffix): Checks ifsends withsuffix."hello".endswith("lo") # Output: True
Modifying Strings
s.strip(): Removes whitespace from both ends ofs." hello ".strip() # Output: "hello"s.replace(old, new): Replaces all occurrences ofoldwithnewins."hello".replace("e", "a") # Output: "hallo"s.split(separator): Splitssinto a list usingseparator(default is whitespace)."a,b,c".split(",") # Output: ["a", "b", "c"]separator.join(iterable): Joins elements ofiterablewithseparatorbetween each element."-".join(["a", "b", "c"]) # Output: "a-b-c"
Other Useful Methods
s.isalpha(): Checks if all characters insare alphabetic."hello".isalpha() # Output: Trues.isdigit(): Checks if all characters insare digits."123".isdigit() # Output: Trues.isalnum(): Checks if all characters insare alphanumeric."hello123".isalnum() # Output: Trues.swapcase(): Swaps uppercase to lowercase and vice versa."Hello".swapcase() # Output: "hELLO"