The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Create a string | message = "Hello, Python" | View examples |
| Create multiline text | message = "First line\\nSecond line" | View examples |
| Count code points | count = len(message) | View examples |
| Read one character | first = message[0] | View examples |
| Slice a range | prefix = message[:5] | View examples |
| Reverse code points | reversed_text = message[::-1] | View examples |
| Trim surrounding whitespace | clean = raw.strip() | View examples |
| Lowercase text | lowered = name.lower() | View examples |
| Normalize for comparison | matches = left.casefold() == right.casefold() | View examples |
| Check for text | contains = "error" in message | View examples |
| Check a prefix | is_secure = url.startswith("https://") | View examples |
| Find a position | position = message.find("Python") | View examples |
| Replace text | updated = message.replace("draft", "ready") | View examples |
| Split fields | fields = line.split(",") | View examples |
| Split once | key, value = line.split("=", maxsplit=1) | View examples |
| Join strings | path = "/".join(parts) | View examples |
| Interpolate values | message = f"{name} has {count} tasks" | View examples |
| Format a number | label = f"Total: ${total:,.2f}" | View examples |
| Encode text | payload = message.encode("utf-8") | View examples |
| Decode bytes | message = 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
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.
message = "Hello, Python"
multiline = """First line
Second line"""
print(message)
print(multiline)
print(len(message)) Hello, Python
First line
Second line
13Index 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.
message = "Hello, Python"
first = message[0]
prefix = message[:5]
reversed_text = message[::-1]
print(first)
print(prefix)
print(reversed_text) H
Hello
nohtyP ,olleHNormalize 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.
raw = " Straße "
clean = raw.strip()
lowered = clean.lower()
left = "Straße"
right = "STRASSE"
print(clean)
print(lowered)
print(left.casefold() == right.casefold()) Straße
straße
TrueSearch 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.
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")) True
True
7
ready: Python guideSplit 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.
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) ['name', 'Ada', 'engineer']
theme dark=high-contrast
docs/python/stringsFormat 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.
name = "Ada"
count = 3
total = 12345.6
message = f"{name} has {count} tasks"
label = f"Total: ${total:,.2f}"
print(message)
print(label) Ada has 3 tasks
Total: $12,345.60Encode 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.
message = "Olá, 世界"
payload = message.encode("utf-8")
restored = payload.decode("utf-8")
print(payload)
print(restored) b'Ol\xc3\xa1, \xe4\xb8\x96\xe7\x95\x8c'
Olá, 世界Local code tester
Try Python string operations
Edit and run the text locally to practice normalization, splitting, joining, and formatting.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



