Working with strings
Course contents (15 lessons)
- Getting started
- Installing Python 3.13 and running your first script
- Variables and basic data types
- Text, numbers and user input
- Working with strings
- Numbers and arithmetic
- Input and output: talking to the user
- Making decisions and repeating work
- Making decisions with if, elif and else
- Loops: for, while, break and continue
- Collections of data
- Lists and tuples
- Dictionaries and sets
- Functions and modules
- Writing your own functions
- Modules, pip and virtual environments
- Files and errors
- Reading and writing files
- Errors and exceptions
- Final project: expense tracker
- Project: build the expense tracker, part 1
- Project: summaries, search and improvements
Text is everywhere
Names, addresses, file paths, messages and invoice descriptions are all text. Python calls text a string, written str. You make one by putting characters inside single or double quotes.
shop = "Murtaza Stationers"
city = 'Lahore'
note = "It's open until 9 pm" # double quotes let you use an apostrophe
path = "C:\\invoices\\2025" # a backslash needs to be doubled
address = """12 Mall Road,
Lahore""" # triple quotes can span lines
Single and double quotes are the same thing. Pick one style and stay with it. I use double quotes.
Joining and repeating
The + operator joins strings. The * operator repeats them.
print("Invoice" + " " + "#" + "104")
print("-" * 20)
f-strings: the easy way to build text
Joining many pieces with + gets messy, and you must convert numbers with str() every time. An f-string fixes both problems. Put an f before the opening quote and write variables inside curly braces.
customer = "Ali Traders"
item = "A4 paper ream"
quantity = 4
unit_price = 1250.5
total = quantity * unit_price
print(f"Customer: {customer}")
print(f"{quantity} x {item} @ {unit_price:.2f}")
print(f"Total: Rs {total:,.2f}")
print(f"{item.upper():<20}|{quantity:>5}|")
Output:
Customer: Ali Traders
4 x A4 paper ream @ 1250.50
Total: Rs 5,002.00
A4 PAPER REAM | 4|
Reading the format codes
The part after the colon inside the braces is a format specifier. .2f means "a float with two digits after the point". , adds thousands separators. <20 pads the text on the right to 20 characters and left-aligns it, while >5 right-aligns in 5 characters. You can put any expression inside the braces, even a method call, as the last line shows.
Indexing and slicing
Every character has a position, counted from zero. You can read one character with square brackets, or a range with a slice.
code = "INV-2025-0042"
print(code[0]) # I
print(code[-1]) # 2 (negative counts from the end)
print(code[0:3]) # INV (start included, end excluded)
print(code[4:8]) # 2025
print(code[-4:]) # 0042
print(len(code)) # 13
The end of a slice is not included. That feels odd at first. A helpful way to remember it: code[0:3] has length 3 - 0 = 3.
Useful methods
Strings come with many built-in actions called methods. You call them with a dot.
| Method | What it does | Example result |
|---|---|---|
upper(), lower() | Change case | "abc".upper() gives "ABC" |
strip() | Remove spaces at both ends | " hi ".strip() gives "hi" |
replace(a, b) | Swap text | "a-b".replace("-", "/") gives "a/b" |
split(sep) | Break into a list | "a,b".split(",") gives ["a", "b"] |
startswith(x) | Check the beginning | "INV-1".startswith("INV") gives True |
find(x) | Position of text, or -1 | "hello".find("l") gives 2 |
You can also test membership with in: "2025" in code is True.
Strings cannot be changed
This is the mistake I see most. A string is immutable, meaning you cannot change a character in place. Methods return a new string and leave the old one alone.
name = " murtaza "
name.strip() # result thrown away
print(repr(name)) # ' murtaza ' - unchanged
name = name.strip() # keep the result
print(repr(name)) # 'murtaza'
Likewise code[0] = "X" raises a TypeError. To change text, build a new string.
Escape characters
Inside a string, a backslash starts a special sequence. \n is a new line and \t is a tab. That is why Windows paths cause trouble: "C:\new" contains a newline. Double the backslash, or use a raw string such as r"C:\new", or just use forward slashes, which Python accepts on Windows.
Try it yourself
Take the string " ali raza, lahore, 0300-1234567 ". Strip it, split it on commas, strip each piece, and print a neat line like Name: Ali Raza | City: Lahore | Phone: 0300-1234567 using an f-string. Use title() to capitalise the name and city.
customer = "Ali Traders"
item = "A4 paper ream"
quantity = 4
unit_price = 1250.5
total = quantity * unit_price
print(f"Customer: {customer}")
print(f"{quantity} x {item} @ {unit_price:.2f}")
print(f"Total: Rs {total:,.2f}")
print(f"{item.upper():<20}|{quantity:>5}|")
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account