Strings
Overview
Text is everywhere in programs: names, messages, file contents, web pages. In Python, text is a string (str) — a sequence of characters. This lesson covers creating strings, putting them together, and taking them apart.
Creating strings
greeting = "Hello"
reply = 'Hi there'
quote = "It's raining" # use double quotes when the text has an apostrophe
speech = 'She said "yes"' # and single quotes when it has double quotes
poem = """Roses are red,
violets are blue.""" # triple quotes for text over several linesSingle and double quotes are equivalent; pick one style (most projects use double) and switch only when the text contains that quote.
Escape sequences
A backslash starts a special character:
| Escape | Meaning |
|---|---|
\n |
new line |
\t |
tab |
\" / \' |
a quote inside quotes of the same kind |
\\ |
a backslash itself |
print("Line one\nLine two")
print("Path: C:\\Users\\asha")For Windows paths and regular expressions, raw strings ignore escapes: r"C:\Users\asha".
Combining strings
first = "Ada"
last = "Lovelace"
first + " " + last # 'Ada Lovelace' — concatenation
"ha" * 3 # 'hahaha' — repetition
f"{first} {last}" # 'Ada Lovelace' — f-stringf-strings
Put an f before the quotes and you can write expressions in curly braces; Python replaces each with its value:
name = "Asha"
age = 29
print(f"{name} is {age} years old.")
print(f"In ten years: {age + 10}")
print(f"Name in capitals: {name.upper()}")f-strings are the clearest way to build text, and they convert numbers automatically — no str() needed, unlike +:
"Age: " + age # TypeError: can only concatenate str (not "int") to str
f"Age: {age}" # 'Age: 29'They can also format numbers (f"{price:.2f}") — see Formatting output.
Length
len("Python") # 6
len("") # 0 — the empty string
len("a b") # 3 — spaces countIndexing: one character
Each character has a position, its index, starting at 0. Negative indexes count from the end:
word = "PYTHON"
word[0] # 'P'
word[5] # 'N'
word[-1] # 'N' — the last character
word[-2] # 'O'
word[6] # IndexError: string index out of rangeSlicing: part of a string
word[start:stop] takes the characters from start up to — but not including — stop:
word[0:2] # 'PY'
word[2:5] # 'THO'
word[:3] # 'PYT' — from the start
word[3:] # 'HON' — to the end
word[:] # 'PYTHON' — a copy of the whole thing
word[::2] # 'PTO' — every second character (the third number is the step)
word[::-1] # 'NOHTYP' — backwardsWhy does the stop position not count? Because then word[:3] + word[3:] is always the whole string, and word[a:b] has exactly b - a characters. Slices never raise errors for out-of-range positions; they just return what exists.
Strings are immutable
You can’t change a string in place:
word = "Python"
word[0] = "J" # TypeError: 'str' object does not support item assignmentInstead, build a new string:
word = "J" + word[1:] # 'Jython'The same goes for string methods: they return a new string and leave the original alone.
name = "asha"
name.upper() # 'ASHA' — but name is still 'asha'
name = name.upper() # keep the result by reassigningA first look at methods
A method is a function that belongs to a value, called with a dot:
"hello".upper() # 'HELLO'
"HELLO".lower() # 'hello'
"ada lovelace".title() # 'Ada Lovelace'
"ada".capitalize() # 'Ada'
" hi ".strip() # 'hi'
"banana".count("a") # 3
"Py" in "Python" # True — 'in' checks for a substringString methods in chapter 7 covers many more.
Remember: indexes start at 0, slices stop before the stop position, and string methods give you a new string — they never change the old one.
Fun with a name
Given first = "ada" and last = "lovelace": (1) build the full name with a capital first letter on each part using an f-string, and print Full name: Ada Lovelace; (2) print the initials A.L.; (3) print how many letters the full name has, not counting the space; (4) print the last name backwards; (5) print the first three letters of the last name in upper case. Use indexing, slicing, len() and string methods — no loops needed.
first = "ada"
last = "lovelace"
# 1. Full name with capitals, using an f-string
# 2. Initials
# 3. Number of letters (no space)
# 4. Last name backwards
# 5. First three letters of the last name, upper casefirst = "ada"
last = "lovelace"
# 1. Full name with capitals, using an f-string
full_name = f"{first.capitalize()} {last.capitalize()}"
print(f"Full name: {full_name}") # Full name: Ada Lovelace
# 2. Initials
print(f"{first[0].upper()}.{last[0].upper()}.") # A.L.
# 3. Number of letters (no space)
print(len(first) + len(last)) # 11
# 4. Last name backwards
print(last[::-1]) # ecalevol
# 5. First three letters of the last name, upper case
print(last[:3].upper()) # LOVSummary
- Strings hold text in single, double or triple quotes; use
\nfor a new line and\"or the other quote type for quotes inside. - f-strings like
f"Hi {name}"insert values into text — the clearest way to build strings. len(s)counts characters;s[0]is the first,s[-1]the last.- Slices
s[start:stop:step]take part of a string; the stop position is not included. - Strings are immutable: methods like
upper()return a new string rather than changing the original.