String Manipulation

Python string formatting, methods, and regular expressions.

f-strings (Python 3.6+)

name = "Ada"
age = 30
print(f"{name} is {age}")          # Ada is 30
print(f"{name!r}")                   # 'Ada' (repr)
print(f"{3.14159:.2f}")             # 3.14

Common Methods

s = "  Hello, World  "

s.strip()            # "Hello, World"
s.lower()            # "  hello, world  "
s.upper()            # "  HELLO, WORLD  "
s.replace("o", "0")  # "  Hell0, W0rld  "
s.split(", ")        # ["  Hello", "World  "]
", ".join(["a","b"]) # "a, b"
s.startswith("  H")  # True
s.find("World")       # 9 (-1 if not found)

Slicing

word = "developer"
word[0:4]     # "deve"
word[-3:]     # "per"
word[::-1]    # "repoleved"

Regex

import re

re.search(r"\d+", "abc123")      # <Match '123'>
re.findall(r"\d+", "a1b2c3")      # ['1', '2', '3']
re.sub(r"\d+", "#", "a1b2c3")     # 'a#b#c#'

Next: Classes & Modules