Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. Python
  4. Python String Methods Cheat Sheet
PythonCheat Sheet

Python String Methods Cheat Sheet

Quick-reference for every string method you actually use. Each section includes copy-ready snippets with inline output comments.

On this page
  1. 1Creating Strings
  2. 2String Methods: Case
  3. 3String Methods: Search
  4. 4String Methods: Split and Join
  5. 5String Methods: Strip and Pad
  6. 6String Methods: Replace and Remove
  7. 7String Formatting: f-strings
  8. 8String Formatting: format()
  9. 9String Slicing
  10. 10String Checks
  11. 11String Encoding
  12. 12String Splitting: Partition
Creating StringsString Methods: CaseString Methods: SearchString Methods: Split and JoinString Methods: Strip and PadString Methods: Replace and RemoveString Formatting: f-stringsString Formatting: format()String SlicingString ChecksString EncodingString Splitting: Partition

Creating Strings

Python strings are immutable sequences of Unicode characters. Use single quotes, double quotes, or triple quotes.

Single and double quotes
a = 'hello'
b = "world"
c = 'it\'s'        # => "it's"
d = "she said \"hi\""  # => 'she said "hi"'
Triple-quoted (multiline) strings
text = """Line one
Line two
Line three"""
len(text.splitlines())   # => 3
Raw strings (ignore backslashes)
path = r"C:\Users\brett\docs"
path   # => 'C:\\Users\\brett\\docs'

Raw strings are useful for regex patterns and Windows file paths.

String repetition and concatenation
dash = '-' * 20       # => '--------------------'
full = 'hello' + ' ' + 'world'   # => 'hello world'

String Methods: Case

upper() and lower()
'hello'.upper()   # => 'HELLO'
'HELLO'.lower()   # => 'hello'
capitalize() and title()
'hello world'.capitalize()   # => 'Hello world'
'hello world'.title()        # => 'Hello World'
swapcase()
'Hello World'.swapcase()   # => 'hELLO wORLD'
casefold() for locale-safe comparison
'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.

find() and rfind()
s = 'hello world hello'
s.find('hello')    # => 0
s.rfind('hello')   # => 12
s.find('xyz')      # => -1
index() raises on miss
s = 'hello world'
s.index('world')   # => 6
# s.index('xyz')   # raises ValueError

Prefer find() when the substring might not exist. Use index() only when absence is a bug.

count()
'banana'.count('a')      # => 3
'banana'.count('an')     # => 1
startswith() and endswith()
'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.

Split on whitespace (default)
s = "hello world foo"
words = s.split()   # => ['hello', 'world', 'foo']
Split on delimiter with limit
s = "a:b:c:d"
parts = s.split(':', 2)   # => ['a', 'b', 'c:d']
Join list into string
words = ['hello', 'world']
result = ' '.join(words)   # => 'hello world'
Split lines (handles \n, \r\n)
text = "line1\nline2\nline3"
lines = text.splitlines()   # => ['line1', 'line2', 'line3']
rsplit() from the right
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.

strip(), lstrip(), rstrip()
'  hello  '.strip()    # => 'hello'
'  hello  '.lstrip()   # => 'hello  '
'  hello  '.rstrip()   # => '  hello'
Strip specific characters
'###hello###'.strip('#')   # => 'hello'
'www.example.com'.lstrip('w.')   # => 'example.com'

strip() removes any combination of the given characters, not a substring.

ljust(), rjust(), center()
'hi'.ljust(10, '-')    # => 'hi--------'
'hi'.rjust(10, '-')    # => '--------hi'
'hi'.center(10, '-')   # => '----hi----'
zfill() for zero-padding
'42'.zfill(5)    # => '00042'
'-42'.zfill(5)   # => '-0042'

String Methods: Replace and Remove

replace(old, new)
'hello world'.replace('world', 'Python')   # => 'hello Python'
'aaa'.replace('a', 'b', 2)                # => 'bba'
removeprefix() and removesuffix() (Python 3.9+)
'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.

translate() and maketrans()
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.

Basic f-string interpolation
name = 'Alice'
age = 30
f"{name} is {age} years old"   # => 'Alice is 30 years old'
Format specs: decimals, alignment, thousands
pi = 3.14159
f"{pi:.2f}"          # => '3.14'
f"{'hi':>10}"        # => '        hi'
f"{1000000:,}"       # => '1,000,000'
Expressions and method calls inside braces
items = ['a', 'b', 'c']
f"{len(items)} items: {', '.join(items)}"   # => '3 items: a, b, c'
Debug format with = (Python 3.8+)
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.

Positional arguments
'{0} then {1}'.format('first', 'second')   # => 'first then second'
'{} and {}'.format('A', 'B')               # => 'A and B'
Keyword arguments
'{name} is {age}'.format(name='Alice', age=30)   # => 'Alice is 30'
Format spec inside format()
'{:>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.

Basic slicing
s = 'abcdef'
s[1:4]    # => 'bcd'
s[:3]     # => 'abc'
s[3:]     # => 'def'
Negative indices
s = 'abcdef'
s[-3:]    # => 'def'
s[:-2]    # => 'abcd'
Step (stride)
s = 'abcdef'
s[::2]    # => 'ace'
s[1::2]   # => 'bdf'
Reverse a string
'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.

Character type checks
'hello'.isalpha()    # => True
'123'.isdigit()      # => True
'abc123'.isalnum()   # => True
'   '.isspace()      # => True
Case checks
'HELLO'.isupper()   # => True
'hello'.islower()   # => True
'Hello World'.istitle()   # => True
Numeric checks: isdigit vs isnumeric vs isdecimal
'²'.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.

encode() and decode()
b = 'café'.encode('utf-8')    # => b'caf\xc3\xa9'
b.decode('utf-8')              # => 'café'
ord() and chr()
ord('A')   # => 65
chr(65)    # => 'A'
chr(128013)  # => '🐍'
Encode with error handling
'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.

partition()
'key=value'.partition('=')    # => ('key', '=', 'value')
'no-sep'.partition('=')      # => ('no-sep', '', '')
rpartition() from the right
'a.b.c'.rpartition('.')   # => ('a.b', '.', 'c')

rpartition() is handy for splitting file.ext or module.submodule paths.

Unpack partition results
header, _, body = 'Subject: Hello'.partition(': ')
header   # => 'Subject'
body     # => 'Hello'
Learn Python in Depth
Python Collections Practice →Python Comprehensions Practice →
Warm-up1 / 2

Can you write this from memory?

Write an expression that splits `item` by commas into a list of strings

See Also
f-strings →List Comprehensions →File I/O →

Start Practicing Python

Free daily exercises with spaced repetition. No credit card required.

← Back to Python Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.