Working with text¶
Goal: join, measure, tidy, and take apart strings.
Why this matters¶
Most of the data a program handles is text: names, messages, file contents, web pages. Python treats text as a first-class citizen, and a handful of tools will cover almost everything you need.
Joining and repeating¶
You met + for numbers. On strings, + joins them end to end. * repeats a string:
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
print("=" * 20)
print("ha" * 3)
Joining is called concatenation. Notice the " " in the middle: Python does not add spaces for you.
first + last would give AdaLovelace.
TypeError: can only concatenate str (not "int") to str
You tried "Age: " + 36. Python will not silently turn the number into text. Either convert it with str(36),
or better, use an f-string: f"Age: {age}". F-strings handle the conversion for you and are almost always the cleaner choice.
How long is it?¶
len() returns the number of characters in a string:
word = "Python"
sentence = "Hello, World!"
print(len(word))
print(len(sentence))
print(len(""))
Spaces and punctuation count. The empty string "" has length 0.
String methods¶
Strings come with built-in actions called methods. You call a method by writing a dot after the value, then the method name, then parentheses:
name = " ada lovelace "
print(name.upper())
print(name.lower())
print(name.strip())
print(name.strip().title())
print(name.replace("ada", "Ada"))
print(name)
| Method | What it does |
|---|---|
.upper() |
all capital letters |
.lower() |
all lowercase letters |
.strip() |
remove spaces from both ends |
.title() |
capitalize the first letter of each word |
.replace(old, new) |
swap every old for new |
Two things to notice.
Methods can be chained. name.strip().title() strips first, then title-cases the result. Read chains left to right.
Methods do not change the original. The last line prints name, and it is still " ada lovelace ".
Strings in Python are immutable: once created, they never change. A method hands you a new string,
and if you want to keep it, you store it:
Cleaning up input
People type stray spaces and random capitals. input("Name: ").strip() is a habit worth forming now.
And answer.lower() == "yes" accepts Yes, YES, and yes all at once.
Discovering more methods¶
Strings have dozens of methods. You do not need to memorize them. In Visual Studio Code, type a string variable
followed by a dot, and a list pops up. Two more that are worth knowing today: .startswith("...") and .endswith("..."),
which return True or False.
Picking out characters¶
Every character in a string has a position, called its index. Counting starts at 0, not 1. Square brackets pull out the character at an index:
word = "Python"
print(word[0])
print(word[1])
print(word[5])
print(word[-1])
print(word[0:3])
print(word[3:])
print(word[:2])
Here is "Python" with its indexes:
word[0]is the first character,word[5]is the last of a six-letter word.- Negative indexes count from the end:
word[-1]is always the last character, whatever the length. word[0:3]is a slice: characters from index 0 up to but not including index 3. That gives three characters.- Leave out the start to mean "from the beginning":
word[:2]. Leave out the end to mean "to the end":word[3:].
The "up to but not including" rule feels odd at first, but it has a nice property: word[:3] + word[3:] is always the whole word.
IndexError: string index out of range
You asked for an index that does not exist, such as word[6] on a six-letter word. Remember the last index is len(word) - 1.
Slices are more forgiving: word[0:100] simply stops at the end.
Try it¶
Store your full name in a variable. Print it in capitals, print how many characters it has, and print just the first three letters.
Common mistakes¶
AttributeError: 'str' object has no attribute 'Upper'
Method names are lowercase: .upper(), not .Upper().
The method did nothing
You wrote name.strip() on its own line and did not store the result. Use name = name.strip().
TypeError: 'str' object is not callable
You wrote len with square brackets or a method without parentheses, or reused len or str as a variable name.
Avoid naming your variables after Python's built-in functions.
Exercises¶
- Shout. Ask for a sentence and print it in capitals with three exclamation marks at the end.
- Character count. Ask for some text and print two numbers: its length including spaces, and its length without spaces.
.replace()can remove the spaces. - Initials. Ask for a first name and a last name. Print the initials in the form
A.L., in capitals, even if the user typed in lowercase with extra spaces.
Solution 2
text = input("Type something: ")
cleaned = text.replace(" ", "")
print(f"Characters including spaces: {len(text)}")
print(f"Characters without spaces: {len(cleaned)}")
Replacing a space with the empty string "" deletes it.
Solution 3
first = input("First name: ").strip()
last = input("Last name: ").strip()
initials = first[0].upper() + "." + last[0].upper() + "."
print(f"Your initials are {initials}")
.strip() runs first so that a name typed as " ada " still has a at index 0.
Summary¶
+joins strings,*repeats them. Use f-strings to mix text and numbers.len(text)counts characters.- Methods are called with a dot:
text.upper(),text.strip(),text.replace(old, new). They return a new string and leave the original alone. - Indexes start at 0.
text[-1]is the last character. - Slices
text[start:end]includestartand stop just beforeend.