Creating Strings
s = "hello"
s = 'hello'
s = """multi
line"""
s = str(42) # "42"
s = r"raw\nstring" # No escape processing
s = b"bytes" # Bytes literal
Searching
| Method | Returns | Description |
|---|
s.find(sub, start?, end?) | int | First index or -1 |
s.rfind(sub) | int | Last index or -1 |
s.index(sub) | int | First index or raises ValueError |
s.rindex(sub) | int | Last index or raises ValueError |
s.count(sub) | int | Number of occurrences |
s.startswith(prefix) | bool | Starts with prefix |
s.endswith(suffix) | bool | Ends with suffix |
sub in s | bool | Contains substring |
"hello world".find("world") # 6
"hello world".count("l") # 3
"hello".startswith("hel") # True
"world" in "hello world" # True
Case Conversion
| Method | Description | Example |
|---|
s.upper() | All uppercase | "HELLO" |
s.lower() | All lowercase | "hello" |
s.capitalize() | First char upper | "Hello" |
s.title() | Title case | "Hello World" |
s.swapcase() | Swap case | "hELLO" |
s.casefold() | Aggressive lowercase (for comparison) | "straße" -> "strasse" |
Trimming & Padding
| Method | Description |
|---|
s.strip() | Remove whitespace both ends |
s.strip(chars) | Remove specific chars both ends |
s.lstrip() | Remove leading whitespace |
s.rstrip() | Remove trailing whitespace |
s.ljust(width, fill?) | Left-justify, pad right |
s.rjust(width, fill?) | Right-justify, pad left |
s.center(width, fill?) | Center, pad both sides |
s.zfill(width) | Pad with zeros on left |
" hello ".strip() # "hello"
"xxhelloxx".strip("x") # "hello"
"42".zfill(5) # "00042"
"hi".center(10, "-") # "----hi----"
Splitting & Joining
"a,b,c".split(",") # ["a", "b", "c"]
"a,b,c".split(",", 1) # ["a", "b,c"] (maxsplit)
"a b c".split() # ["a", "b", "c"] (split on whitespace)
"line1\nline2".splitlines() # ["line1", "line2"]
"a.b.c".rsplit(".", 1) # ["a.b", "c"]
"a.b.c".partition(".") # ("a", ".", "b.c")
"a.b.c".rpartition(".") # ("a.b", ".", "c")
",".join(["a", "b", "c"]) # "a,b,c"
" ".join(["hello", "world"]) # "hello world"
Replacing
"hello".replace("l", "r") # "herro"
"hello".replace("l", "r", 1) # "herlo" (count)
# For regex replacement
import re
re.sub(r"\d+", "#", "abc 123") # "abc #"
Testing
| Method | Description |
|---|
s.isalpha() | All alphabetic |
s.isdigit() | All digits |
s.isalnum() | All alphanumeric |
s.isspace() | All whitespace |
s.isupper() | All uppercase |
s.islower() | All lowercase |
s.istitle() | Title case |
s.isnumeric() | All numeric (includes unicode) |
s.isascii() | All ASCII characters |
s.isidentifier() | Valid Python identifier |
s.isprintable() | All printable characters |
f-Strings (Python 3.6+)
name = "Alice"
age = 30
f"Hello, {name}!" # "Hello, Alice!"
f"{age + 1}" # "31"
f"{name!r}" # "'Alice'" (repr)
f"{name!s}" # "Alice" (str)
f"{3.14159:.2f}" # "3.14"
f"{42:05d}" # "00042"
f"{1000:,}" # "1,000"
f"{0.75:.0%}" # "75%"
f"{'hi':>10}" # " hi"
f"{'hi':<10}" # "hi "
f"{'hi':^10}" # " hi "
f"{'hi':*^10}" # "****hi****"
f"{value = }" # "value = 42" (debug, 3.8+)
| Spec | Description | Example |
|---|
d | Integer | f"{42:d}" -> "42" |
f | Fixed-point | f"{3.14:.1f}" -> "3.1" |
e | Scientific | f"{1234:.2e}" -> "1.23e+03" |
% | Percentage | f"{0.75:.0%}" -> "75%" |
, | Thousands separator | f"{1000:,}" -> "1,000" |
_ | Underscore separator | f"{1000:_}" -> "1_000" |
x | Hex (lowercase) | f"{255:x}" -> "ff" |
X | Hex (uppercase) | f"{255:X}" -> "FF" |
o | Octal | f"{8:o}" -> "10" |
b | Binary | f"{10:b}" -> "1010" |
Slicing
s = "hello world"
s[0] # "h"
s[-1] # "d"
s[0:5] # "hello"
s[6:] # "world"
s[::-1] # "dlrow olleh" (reverse)
s[::2] # "hlowrd" (every 2nd char)
Common Recipes
# Reverse a string
s[::-1]
# Check palindrome
s == s[::-1]
# Remove prefix/suffix (3.9+)
s.removeprefix("http://")
s.removesuffix(".txt")
# Translate characters
table = str.maketrans("abc", "xyz")
"abc".translate(table) # "xyz"
# Multiline string dedent
from textwrap import dedent
dedent("""
hello
world
""").strip()