The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Create a stringmessage = "Hello, Python"View examples
Create multiline textmessage = "First line\\nSecond line"View examples
Count code pointscount = len(message)View examples
Read one characterfirst = message[0]View examples
Slice a rangeprefix = message[:5]View examples
Reverse code pointsreversed_text = message[::-1]View examples
Trim surrounding whitespaceclean = raw.strip()View examples
Lowercase textlowered = name.lower()View examples
Normalize for comparisonmatches = left.casefold() == right.casefold()View examples
Check for textcontains = "error" in messageView examples
Check a prefixis_secure = url.startswith("https://")View examples
Find a positionposition = message.find("Python")View examples
Replace textupdated = message.replace("draft", "ready")View examples
Split fieldsfields = line.split(",")View examples
Split oncekey, value = line.split("=", maxsplit=1)View examples
Join stringspath = "/".join(parts)View examples
Interpolate valuesmessage = f"{name} has {count} tasks"View examples
Format a numberlabel = f"Total: ${total:,.2f}"View examples
Encode textpayload = message.encode("utf-8")View examples
Decode bytesmessage = payload.decode("utf-8")View examples

Python str values are immutable sequences of Unicode code points. Build new strings instead of expecting methods to mutate existing text, choose normalization rules that match the domain, and keep text distinct from encoded bytes at file and network boundaries.

Step by step

Detailed examples

01

Create and measure Unicode strings

Single and double quotes create equivalent string values, while triple quotes can contain physical line breaks. len counts Unicode code points, not encoded bytes or user-perceived grapheme clusters, so visible characters such as combined emoji may require specialized segmentation.

Literal, multiline text, and length
message = "Hello, Python"
multiline = """First line
Second line"""
print(message)
print(multiline)
print(len(message))
Output
Hello, Python
First line
Second line
13
Back to quick reference ↑
02

Index and slice without mutation

Indexes begin at zero and negative indexes count from the end. A slice excludes its stop position and returns a new string. Reversing with a negative step reverses code points, which may not preserve the visual order of multi-code-point grapheme clusters.

Index, prefix, and reverse
message = "Hello, Python"
first = message[0]
prefix = message[:5]
reversed_text = message[::-1]
print(first)
print(prefix)
print(reversed_text)
Output
H
Hello
nohtyP ,olleH
Back to quick reference ↑
03

Normalize whitespace and case deliberately

strip removes surrounding whitespace but leaves internal spacing unchanged. lower is suitable for presentation transformations, while casefold is designed for caseless Unicode comparison. Case normalization alone is not locale-aware collation or full Unicode normalization.

Trim and compare names
raw = "  Straße  "
clean = raw.strip()
lowered = clean.lower()
left = "Straße"
right = "STRASSE"
print(clean)
print(lowered)
print(left.casefold() == right.casefold())
Output
Straße
straße
True
Back to quick reference ↑
04

Search and replace exact substrings

Membership is the clearest existence test, startswith handles prefixes, and find returns a numeric position when that position matters. replace creates a new string and replaces every match unless count limits it; use regular expressions only when literal operations cannot express the pattern.

Inspect and update a status message
message = "draft: Python guide"
url = "https://example.com/docs"
print("Python" in message)
print(url.startswith("https://"))
print(message.find("Python"))
print(message.replace("draft", "ready"))
Output
True
True
7
ready: Python guide
Back to quick reference ↑
05

Split structured text and join string items

split with an explicit separator preserves empty fields between adjacent delimiters, while split without one collapses whitespace runs. maxsplit protects delimiters that may appear later in a value. join belongs to the separator and requires every item to already be a string.

Parse fields and rebuild a path
line = "name,Ada,engineer"
fields = line.split(",")
key, value = "theme=dark=high-contrast".split("=", maxsplit=1)
path = "/".join(["docs", "python", "strings"])
print(fields)
print(key, value)
print(path)
Output
['name', 'Ada', 'engineer']
theme dark=high-contrast
docs/python/strings
Back to quick reference ↑
06

Format values with f-strings

An f-string evaluates expressions in the current scope and applies the format specification after a colon. Keep complex business logic outside the interpolation, and never evaluate an f-string or format template supplied by an untrusted user.

Text and numeric formatting
name = "Ada"
count = 3
total = 12345.6
message = f"{name} has {count} tasks"
label = f"Total: ${total:,.2f}"
print(message)
print(label)
Output
Ada has 3 tasks
Total: $12,345.60
Back to quick reference ↑
07

Encode only at text boundaries

str represents Unicode text and bytes represents encoded data. Encode when writing to a byte-oriented protocol or storage boundary and decode when reading from it, using the encoding required by that boundary. A mismatched encoding can raise UnicodeError or silently produce incorrect text.

UTF-8 round trip
message = "Olá, 世界"
payload = message.encode("utf-8")
restored = payload.decode("utf-8")
print(payload)
print(restored)
Output
b'Ol\xc3\xa1, \xe4\xb8\x96\xe7\x95\x8c'
Olá, 世界
Back to quick reference ↑

Local code tester

Try Python string operations

Edit and run the text locally to practice normalization, splitting, joining, and formatting.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software FoundationText Sequence Type — strdocs.python.org
  2. Python Software FoundationString Methodsdocs.python.org
  3. Python Software FoundationFormat String Syntaxdocs.python.org
  4. Python Software FoundationUnicode HOWTOdocs.python.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback