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 ins
to lowercase."Hello".lower() # Output: "hello"
s.upper()
: Converts all characters ins
to 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 ofsub
ins
(or-1
if not found)."hello".find("e") # Output: 1
s.count(sub)
: Counts the occurrences ofsub
ins
."banana".count("a") # Output: 3
s.startswith(prefix)
: Checks ifs
starts withprefix
."hello".startswith("he") # Output: True
s.endswith(suffix)
: Checks ifs
ends 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 ofold
withnew
ins
."hello".replace("e", "a") # Output: "hallo"
s.split(separator)
: Splitss
into a list usingseparator
(default is whitespace)."a,b,c".split(",") # Output: ["a", "b", "c"]
separator.join(iterable)
: Joins elements ofiterable
withseparator
between each element."-".join(["a", "b", "c"]) # Output: "a-b-c"
Other Useful Methods
s.isalpha()
: Checks if all characters ins
are alphabetic."hello".isalpha() # Output: True
s.isdigit()
: Checks if all characters ins
are digits."123".isdigit() # Output: True
s.isalnum()
: Checks if all characters ins
are alphanumeric."hello123".isalnum() # Output: True
s.swapcase()
: Swaps uppercase to lowercase and vice versa."Hello".swapcase() # Output: "hELLO"