Text. Anything in quotes. Single or double — Python doesn't care, but pick one and be consistent.
name = "Alice"
greeting = 'Hello there'
long_text = """This is a multi-line string.
It can wrap across as many lines as you like."""
first = "Alice"
last = "Smith"
full = first + " " + last # "Alice Smith"
Put an f right before the opening quote, and you can drop variables straight inside {}:
name = "Alice"
sales = 1234.567
print(f"{name} sold ${sales:,.2f}")
# Alice sold $1,234.57
F-strings replaced the older "{} sold ${:.2f}".format(name, sales) style. Use f-strings everywhere.
| Method | What it does | Example | Result |
|---|---|---|---|
.upper() | UPPERCASE | "hi".upper() | "HI" |
.lower() | lowercase | "Hi".lower() | "hi" |
.title() | Title Case | "alice smith".title() | "Alice Smith" |
.strip() | Trim whitespace | " abc ".strip() | "abc" |
.replace(a, b) | Substitute | "$1,200".replace(",", "") | "$1200" |
.split(",") | Break into a list | "a,b,c".split(",") | ["a","b","c"] |
" ".join([...]) | Glue list back into a string | " ".join(["a","b"]) | "a b" |
.startswith("X") | Boolean check | "acme.csv".endswith(".csv") | True |
Like grabbing a substring with MID() or LEFT() in Excel.
name = "Anthropic"
name[0] # 'A' — first character
name[-1] # 'c' — last character
name[0:4] # 'Anth' — first four
name[4:] # 'ropic' — from index 4 to the end
name[::-1] # 'cipohtnA' — reversed (a Python party trick)
raw = " alice SMITH "
step1 = raw.strip() # "alice SMITH"
step2 = step1.lower() # "alice smith"
step3 = step2.title() # "Alice Smith"
print(step3)
cleaned = raw.strip().lower().title()
print(cleaned) # Alice Smith
Chaining like this — calling one method on the result of another — is a Python superpower. You'll see it constantly in pandas.
f"Hi {name}"..upper(), .strip(), .replace() do most of the cleaning work.s[0:4] — pulls out substrings.Given " Alice@Example.COM ", write the Python that turns it into a clean lowercase, trimmed email.
" Alice@Example.COM ".strip().lower()
# 'alice@example.com'