str#
str is immutable Unicode. The operator’s most-touched data
type. Six literal forms, an extensive method surface, slicing,
and f-strings with a format spec mini-language. Mixing with
bytes always requires an explicit encode or decode.
Quoting and escapes#
Single, double, and triple-quoted strings are identical aside from what they can contain without escaping.
s = "hello"
s2 = 'also fine' # single quotes equivalent
ml = """multi
line""" # newlines preserved
r = r"\n is literal" # raw: backslash is not an escape
esc = "tab\there, newline\n" # \t \n \xNN \uNNNN \UNNNNNNNN
Raw strings (r"...") are the default for regex patterns,
Windows paths, and anywhere a backslash should mean itself.
f-strings and format spec#
f-strings are the default. The = self-debug form and the
format spec mini-language cover most needs. Examples assume
n, pi = 42, 3.14159 and y = ... for the conversion
forms.
Form |
Example |
Result |
|---|---|---|
Plain |
|
|
Width, right-align |
|
|
Width, left-align |
|
|
Zero-pad |
|
|
Explicit fill + align |
|
|
Hex |
|
|
Binary |
|
|
Fixed-point |
|
|
Scientific |
|
|
Thousands separator |
|
|
Percent |
|
|
Self-debug |
|
|
|
|
|
|
|
|
|
|
|
Datetime values format with their own strftime codes.
Examples assume t = datetime(2026, 5, 19, 14, 35).
Code |
Example |
Result |
|---|---|---|
|
|
|
|
|
|
Format spec syntax: [fill][align][sign][#][0][width][,][.precision][type].
align is < left, > right, ^ centre, = for
numeric sign-fill. type is the conversion (s string,
d int, f float, e scientific, x hex, b
binary, o octal, % percent).
Methods#
The operator’s daily kit on str. Examples below assume
s = " Hello, Operator ".
Method |
Example |
Effect |
|---|---|---|
|
|
|
|
|
Trim leading whitespace only. |
|
|
Trim trailing whitespace only. |
|
|
Lowercase. |
|
|
Uppercase. |
|
|
Title case. |
|
|
Aggressive lowercase for caseless comparison. |
|
|
Split on |
|
|
Right-to-left split with a cap on splits. |
|
|
Concatenate an iterable of strings with a separator. |
|
|
Replace every occurrence; pass a count to cap. |
|
|
Prefix test; accepts a tuple of prefixes. |
|
|
Suffix test; accepts a tuple of suffixes. |
|
|
First index of substring or |
|
|
First index of substring; raises |
|
|
Non-overlapping occurrence count. |
|
|
Character count (built-in, not a method). |
|
|
Left-pad with |
|
|
Centre-pad to width with a fill char. |
|
|
Left-justify to width. |
|
|
Per-character substitution via a translation table. |
Slicing#
The other half of string work. Examples assume
s = "abcdefg".
Form |
Example |
Result |
|---|---|---|
Index |
|
|
Negative index |
|
|
Range slice |
|
|
Stride |
|
|
Reverse |
|
|
Building#
Build long strings with join over a sequence, not by
repeated += in a loop. += allocates a new string each
time; join walks once and concatenates into a single buffer.
"-".join(parts) # one allocation
"".join(f"<{tag}>{v}</{tag}>" for tag, v in fields)
When the parts arrive incrementally (a streaming writer, a
recursive walk), use io.StringIO as an accumulator and call
getvalue() at the end.
import io
buf = io.StringIO()
buf.write("HEAD ")
buf.write(path)
buf.write(" HTTP/1.1\r\n")
wire = buf.getvalue()
Regex#
re is the stdlib regex engine. Compile patterns once when
they’re reused; named groups make extraction readable.
import re
IPV4 = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
for line in lines:
for ip in IPV4.findall(line):
print(ip)
m = re.match(r"(?P<user>\w+)@(?P<host>[\w.-]+)", "op@example.com")
if m:
print(m["user"], m["host"])
Method cheat sheet.
Call |
Returns |
|---|---|
|
|
|
first |
|
|
|
list of matched groups (or whole match if no groups) |
|
iterator of |
|
|
|
|
|
reusable pattern object (use it for hot loops) |
Flags.
Flag |
Effect |
|---|---|
|
Case-insensitive match. |
|
|
|
|
|
Free-spacing with inline comments. |
The deeper regex surface (lookahead, backrefs, atomic groups, flavour differences across engines) lives in Regex.
Method catalog#
The complete instance-method surface on str, grouped by
purpose.
Case#
Method |
Effect |
|---|---|
|
Lowercase using simple case folding. |
|
Uppercase. |
|
Title case (capitalise each word). |
|
Uppercase the first character; lowercase the rest. |
|
Swap case of every character. |
|
Aggressive lowercase for caseless comparison. |
Trim and pad#
Method |
Effect |
|---|---|
|
Trim leading and trailing chars (whitespace by default). |
|
Trim leading chars only. |
|
Trim trailing chars only. |
|
Strip |
|
Strip |
|
Left-justify to width with a fill char. |
|
Right-justify to width. |
|
Centre to width. |
|
Left-pad with |
|
Replace tabs with spaces. |
Split and join#
Method |
Effect |
|---|---|
|
Split on |
|
Split from the right. |
|
Split on universal newlines. |
|
Split into |
|
Split at the last |
|
Concatenate iterable of strings with this string between. |
Search and replace#
Method |
Effect |
|---|---|
|
Lowest index of |
|
Highest index of |
|
Like |
|
Like |
|
Non-overlapping occurrence count. |
|
Prefix test; accepts a tuple of prefixes. |
|
Suffix test; accepts a tuple of suffixes. |
|
Replace occurrences; |
|
Per-character substitution via a |
Predicates#
Method |
|
|---|---|
|
All characters are letters and string is non-empty. |
|
All characters are digits. |
|
All characters are decimal digits. |
|
All characters are numeric (broader than |
|
All characters are alphanumeric. |
|
All characters are whitespace. |
|
All characters are ASCII. |
|
All cased characters are lowercase. |
|
All cased characters are uppercase. |
|
Title-cased. |
|
Valid as a Python identifier. |
|
Every character is printable. |
Encoding and formatting#
Method |
Effect |
|---|---|
|
Encode to |
|
Legacy |
|
|
|
Build a translation table for |
A few representative method examples; the full surface is too broad to walk through here.
split cuts on the first argument; rsplit with a
maxsplit cap keeps the rest intact.
"a,b,c,d".rsplit(",", 1)
['a,b,c', 'd']
partition splits into a three-tuple at the first occurrence.
"key=value=extra".partition("=")
('key', '=', 'value=extra')
translate with a str.maketrans table substitutes
character-by-character.
"hello".translate(str.maketrans("el", "3L"))
'h3LLo'
encode rounds to bytes; decode rounds back.
"café".encode("utf-8")
b'caf\xc3\xa9'
Operator overloading#
The dunder methods str implements.
Operator |
Dunder |
Returns |
|---|---|---|
|
|
Concatenation. |
|
|
Repetition. |
|
|
Equality. |
|
|
Lexicographic less than. |
|
|
Hash for set / dict membership. |
|
|
Substring membership test. |
|
|
Indexing and slicing. |
|
|
Character count. |
|
|
Character iteration. |
|
|
Format spec interpolation. |
|
|
Debug and human-readable forms. |
|
|
|
A path class can use __truediv__ for / and __str__
for the rendered form (mirroring pathlib.Path).
class Path:
def __init__(self, parts): self.parts = list(parts)
def __truediv__(self, name): return Path(self.parts + [name])
def __str__(self): return "/".join(self.parts)
str(Path(["var", "log"]) / "auth.log")
'var/log/auth.log'
__format__ lets a class participate in f-string format specs.
class Hex:
def __init__(self, n): self.n = n
def __format__(self, spec): return format(self.n, spec or "x")
f"{Hex(255)}, {Hex(255):08x}"
'ff, 000000ff'