Part 02 / Topic 3 of 10
Strings
A string (str) is text inside quotes: 'hi', "hi", or """many lines""". Think of it as beads on a thread: each character has a position number called an index, starting at 0. Negative indexes count from the end. A slice [start:end] cuts out a piece. An optional third number, the step, says how many to jump: [start:end:step].
B e n g a l u r u
0 1 2 3 4 5 6 7 8
-9 -8 -7 -6 -5 -4 -3 -2 -1
Real-world example: Make a short city code for a courier label.
city = "Bengaluru"
print(city[0], city[-1]) # B u
print(city[0:5]) # Benga (start included, end excluded)
print(city[2:]) # ngaluru
print(city[::2]) # Bnauu (every 2nd letter: step 2)
print(city[::-1]) # urulagneB (step -1: reversed)
print(len(city)) # 9
print(city[:3].upper()) # BEN
| Method | What it does | Example | Result |
|---|---|---|---|
strip() |
Removes spaces at both ends | " hi ".strip() |
'hi' |
split(sep) |
Breaks into a list | "a,b,c".split(",") |
['a', 'b', 'c'] |
join(list) |
Joins a list into one string | "-".join(["a", "b"]) |
'a-b' |
replace(a, b) |
Replaces text | "chai".replace("c", "C") |
'Chai' |
upper() / lower() |
Changes case | "chai".upper() |
'CHAI' |
title() |
Capitalises each word | "new delhi".title() |
'New Delhi' |
capitalize() |
Capital first letter, rest lowercase | "new DELHI".capitalize() |
'New delhi' |
find(x) |
Index of x, or -1 |
"chai".find("a") |
2 |
startswith(x) |
Starts with x? |
"+91 98".startswith("+91") |
True |
count(x) |
How many times | "banana".count("a") |
3 |
A method is a function that belongs to a value; you call it with a dot: city.upper(). split() gives a list of words (Part 4) and join() glues them back.
Immutability: You cannot change a string in place. Methods return a new string.
name = "ravi"
# name[0] = "R" # TypeError: 'str' object does not support item assignment
name = name.capitalize() # โ
make a new string and point the name to it
print(name) # Ravi
print("ab" * 3) # ababab
print("Hi " + "Meera") # Hi Meera
๐ Going deeper: Slices never raise
IndexError:"chai"[2:100]is just'ai', while"chai"[100]fails. Python 3 strings are Unicode, solen("โน500")is4even thoughโนtakes 3 bytes in UTF-8.
Read more: every string method, in the official string methods reference.
Done here? The practice set for Part 2 โ 8 exercises with solutions โ is on the part page.