Chapter 03 ยท Working With Data
Working With Text
Names, messages, addresses, passwords โ a huge amount of programming is handling text. Python gives you friendly tools to slice, join and reshape it.
A string is a line of beads on a thread โ each bead is one character. Because it's ordered, you can point to any bead by its position, take a section of the thread, or tie two threads together.
Joining text together
Use + to join strings, or (better) an f-string:
first = "Grace"
last = "Banda"
print(first + " " + last)
print(f"{first} {last}")
Handy things strings can do
Every string comes with built-in methods โ actions you call with a dot:
word = "python"
print(word.upper())
print(word.capitalize())
print(len(word))
.upper()/.lower()โ change the case..capitalize()โ capital first letter.len(word)โ how many characters (note:lenis a function, not a method)..strip()โ remove blank space from the ends..replace("a", "b")โ swap one piece of text for another.
Picking out pieces
Each character has a position (an index) starting at 0:
name = "Zambia"
print(name[0])
print(name[1])
print(name[0:3])
name[0] is the first character. name[0:3] is a slice โ from
position 0 up to (but not including) 3.
Store your full name in a variable. Print it in ALL CAPS, print how many characters long it is, and print just the first letter.
This trips up every beginner: the first character is index 0, not 1. So in
"Zambia", the a at the end is index 5, and there is no index 6.
Recap
- Join text with
+or f-strings. - Methods like
.upper(),.strip(),.replace()reshape text. - Indexing starts at 0; slicing
[start:end]takes a section.