Python String Methods Cheat Sheet
Quick-reference for every string method you actually use. Each section includes copy-ready snippets with inline output comments.
Creating Strings
Python strings are immutable sequences of Unicode characters. Use single quotes, double quotes, or triple quotes.
a = 'hello'
b = "world"
c = 'it\'s' # => "it's"
d = "she said \"hi\"" # => 'she said "hi"'text = """Line one
Line two
Line three"""
len(text.splitlines()) # => 3path = r"C:\Users\brett\docs"
path # => 'C:\\Users\\brett\\docs'Raw strings are useful for regex patterns and Windows file paths.
dash = '-' * 20 # => '--------------------'
full = 'hello' + ' ' + 'world' # => 'hello world'String Methods: Case
'hello'.upper() # => 'HELLO'
'HELLO'.lower() # => 'hello''hello world'.capitalize() # => 'Hello world'
'hello world'.title() # => 'Hello World''Hello World'.swapcase() # => 'hELLO wORLD''Straße'.casefold() # => 'strasse'
'Straße'.lower() # => 'straße'Use casefold() instead of lower() when comparing user input across locales.
String Methods: Search
Find substrings by position or count. Remember: find() returns -1 on miss, index() raises ValueError.
s = 'hello world hello'
s.find('hello') # => 0
s.rfind('hello') # => 12
s.find('xyz') # => -1s = 'hello world'
s.index('world') # => 6
# s.index('xyz') # raises ValueErrorPrefer find() when the substring might not exist. Use index() only when absence is a bug.
'banana'.count('a') # => 3
'banana'.count('an') # => 1'hello.py'.startswith('hello') # => True
'hello.py'.endswith('.py') # => True
'hello.py'.endswith(('.py', '.js')) # => True (tuple of suffixes)String Methods: Split and Join
Split strings into lists, then rejoin them with a delimiter.
s = "hello world foo"
words = s.split() # => ['hello', 'world', 'foo']s = "a:b:c:d"
parts = s.split(':', 2) # => ['a', 'b', 'c:d']words = ['hello', 'world']
result = ' '.join(words) # => 'hello world'text = "line1\nline2\nline3"
lines = text.splitlines() # => ['line1', 'line2', 'line3']path = "a/b/c/d.txt"
path.rsplit('/', 1) # => ['a/b/c', 'd.txt']rsplit() with maxsplit is handy for grabbing the last segment of a path or URL.
String Methods: Strip and Pad
Remove leading/trailing characters or pad strings to a fixed width.
' hello '.strip() # => 'hello'
' hello '.lstrip() # => 'hello '
' hello '.rstrip() # => ' hello''###hello###'.strip('#') # => 'hello'
'www.example.com'.lstrip('w.') # => 'example.com'strip() removes any combination of the given characters, not a substring.
'hi'.ljust(10, '-') # => 'hi--------'
'hi'.rjust(10, '-') # => '--------hi'
'hi'.center(10, '-') # => '----hi----''42'.zfill(5) # => '00042'
'-42'.zfill(5) # => '-0042'String Methods: Replace and Remove
'hello world'.replace('world', 'Python') # => 'hello Python'
'aaa'.replace('a', 'b', 2) # => 'bba''test_hello.py'.removeprefix('test_') # => 'hello.py'
'test_hello.py'.removesuffix('.py') # => 'test_hello'Unlike strip(), these remove an exact substring prefix/suffix, not a character set.
table = str.maketrans('aeiou', '12345')
'hello'.translate(table) # => 'h2ll4'String Formatting: f-strings
f-strings (Python 3.6+) embed expressions directly in string literals. The fastest and most readable formatting option.
name = 'Alice'
age = 30
f"{name} is {age} years old" # => 'Alice is 30 years old'pi = 3.14159
f"{pi:.2f}" # => '3.14'
f"{'hi':>10}" # => ' hi'
f"{1000000:,}" # => '1,000,000'items = ['a', 'b', 'c']
f"{len(items)} items: {', '.join(items)}" # => '3 items: a, b, c'x = 42
f"{x = }" # => 'x = 42'
f"{x * 2 = }" # => 'x * 2 = 84'String Formatting: format()
The format() method uses replacement fields in curly braces. Useful when the template is stored separately from the data.
'{0} then {1}'.format('first', 'second') # => 'first then second'
'{} and {}'.format('A', 'B') # => 'A and B''{name} is {age}'.format(name='Alice', age=30) # => 'Alice is 30''{:>10}'.format('hi') # => ' hi'
'{:.2%}'.format(0.85) # => '85.00%'String Slicing
Slice syntax is s[start:stop:step]. Indices are zero-based and the stop index is exclusive.
s = 'abcdef'
s[1:4] # => 'bcd'
s[:3] # => 'abc'
s[3:] # => 'def's = 'abcdef'
s[-3:] # => 'def'
s[:-2] # => 'abcd's = 'abcdef'
s[::2] # => 'ace'
s[1::2] # => 'bdf''hello'[::-1] # => 'olleh'Reversing with [::-1] is idiomatic Python but creates a new string.
String Checks
Boolean test methods. All return False on empty strings.
'hello'.isalpha() # => True
'123'.isdigit() # => True
'abc123'.isalnum() # => True
' '.isspace() # => True'HELLO'.isupper() # => True
'hello'.islower() # => True
'Hello World'.istitle() # => True'²'.isdigit() # => True (superscript 2)
'²'.isdecimal() # => False
'½'.isnumeric() # => True (fraction 1/2)For validating integer input, isdecimal() is the safest choice.
String Encoding
Convert between str (text) and bytes, or work with character codes.
b = 'café'.encode('utf-8') # => b'caf\xc3\xa9'
b.decode('utf-8') # => 'café'ord('A') # => 65
chr(65) # => 'A'
chr(128013) # => '🐍''café'.encode('ascii', errors='replace') # => b'caf?'
'café'.encode('ascii', errors='ignore') # => b'caf'String Splitting: Partition
partition() splits into exactly three parts: before, separator, after. Useful when you need the delimiter too.
'key=value'.partition('=') # => ('key', '=', 'value')
'no-sep'.partition('=') # => ('no-sep', '', '')'a.b.c'.rpartition('.') # => ('a.b', '.', 'c')rpartition() is handy for splitting file.ext or module.submodule paths.
header, _, body = 'Subject: Hello'.partition(': ')
header # => 'Subject'
body # => 'Hello'Can you write this from memory?
Write an expression that splits `item` by commas into a list of strings