← All lessons
Programming basics · Lesson 7 of 9

Working with text

A string is a sequence of characters, so a lot of what works on lists works on strings too: word[0] is the first letter, len(word) the number of characters, word[1:4] a slice and "a" in word a check.

Strings can't be changed in place, but they have methods that make new strings. upper() and lower() change the case, strip() removes spaces at the ends, and replace(old, new) swaps text.

word = "Python"
print(word[0], len(word))
print(word.upper())
print("  hi  ".strip() + "!")
Prints
P 6
PYTHON
hi!

split() cuts a string into a list of words (or at whatever separator you give it), and "-".join(list) goes the other way, gluing a list of strings together with a separator.

parts = "red,green,blue".split(",")
print(parts)
print(" & ".join(parts))
Prints
['red', 'green', 'blue']
red & green & blue

An f-string puts values into text: write f before the quotes and the variable names in curly brackets. It's the clearest way to build a message, and it converts numbers for you.

name = "Ana"
age = 12
print(f"{name} is {age} years old")
Prints
Ana is 12 years old

Practice

What does this print?

s = "keyboard"
print(s[3:])
More info

Quick reference

s[i], s[a:b], len(s)A character, a slice, the length.
s.upper() / s.lower()Capitals / small letters.
s.strip()Removes spaces from both ends.
s.split(sep)Cuts into a list (at spaces by default).
sep.join(list)Glues a list of strings with sep between.
f"{x}"An f-string: puts the value of x into the text.

The other computer science courses