PY

Strings

Python · 8 entries

f-strings (Formatted String Literals)

syntax
f"text {expression}"
example
name = "Alice"
balance = 1234.5
print(f"User: {name}")
print(f"Balance: ${balance:,.2f}")
print(f"{'centered':^20}")
output
User: Alice
Balance: $1,234.50
      centered      

Note Since Python 3.12, f-strings can contain backslashes and nested quotes freely. You can also nest f-strings inside f-strings.

Common String Methods

syntax
str.method()
example
email = "  Alice@Example.COM  "
print(email.strip().lower())
print("hello world".title())
print("python".startswith("py"))
print("2026-04-04".replace("-", "/"))
output
alice@example.com
Hello World
True
2026/04/04

Note String methods always return new strings since strings are immutable. Chain methods for compact transformations.

String Slicing

syntax
string[start:stop:step]
example
word = "pythonic"
print(word[0:4])
print(word[-4:])
print(word[::2])
print(word[::-1])
output
pyth
onic
ptoi
cinohtyp

Note Slicing never raises IndexError, even if indices exceed the string length. Negative step reverses direction.

Multiline Strings

syntax
"""text
spanning lines"""
example
query = """
    SELECT name, email
    FROM users
    WHERE active = true
""".strip()
print(query)
output
SELECT name, email
    FROM users
    WHERE active = true

Note Triple-quoted strings preserve all whitespace and newlines. Use textwrap.dedent() or .strip() to control leading/trailing space.

Raw Strings

syntax
r"text with \backslashes"
example
path = r"C:\Users\alice\docs"
pattern = r"\d{3}-\d{4}"
print(path)
print(pattern)
output
C:\Users\alice\docs
\d{3}-\d{4}

Note Raw strings treat backslashes as literal characters. Essential for regex patterns and Windows paths. A raw string cannot end with an odd number of backslashes.

Encode & Decode

syntax
str.encode(encoding)
bytes.decode(encoding)
example
text = "caf\u00e9"
encoded = text.encode("utf-8")
print(encoded)
print(encoded.decode("utf-8"))
output
b'caf\xc3\xa9'
caf\u00e9

Note UTF-8 is the default encoding. Use errors='ignore' or errors='replace' to handle characters that cannot be encoded in the target encoding.

Join & Split

syntax
separator.join(iterable)
str.split(separator)
example
words = ["Python", "is", "great"]
sentence = " ".join(words)
print(sentence)

csv_row = "alice,30,engineer"
fields = csv_row.split(",")
print(fields)
output
Python is great
['alice', '30', 'engineer']

Note split() with no arguments splits on any whitespace and removes empty strings. split(',') keeps empty strings between consecutive delimiters.

String Content Checks

syntax
str.isdigit() / str.isalpha() / str.isalnum()
example
pin = "4821"
print(pin.isdigit())
print("hello123".isalnum())
print("  ".isspace())
print("api" in "api_key_value")
output
True
True
True
True

Note The 'in' operator checks for substring presence and is usually more practical than the .is*() family for real-world validation.