>>> Python for Beginners Chapter 03 of 10

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.

๐Ÿงต
Real-world analogy

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}")
Grace Banda Grace Banda

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))
PYTHON Python 6

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])
Z a Zam

name[0] is the first character. name[0:3] is a slice โ€” from position 0 up to (but not including) 3.

โœ๏ธ Try it yourself

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.

Counting starts at zero

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