Strings
A string is a piece of text: a name, a sign on a house, a whole letter. You have printed strings since lesson 1. Now you will take them apart and put them together.
Joining and repeating
+ joins two strings end to end. * repeats a string a number of times.
1first = "Lamp"2second = "lighter"3print(first + second)4print(first + " " + second)5print("-" * 20)6print("ha" * 3)
Lamplighter Lamp lighter -------------------- hahaha
+ adds no space of its own; you add one yourself, as in the second line. Both sides of + must be strings: "Lamp " + 3 is a TypeError, so write "Lamp " + str(3) or use an f-string.
How long is it?
len() counts the characters in a string. Spaces and punctuation count too.
1word = "lamplighter"2print(len(word))3print(len("Hi there!"))4print(len(""))
11 9 0
"" is the empty string: a string with nothing in it, length 0.
One character at a time
Each character has a position, called its index. Counting starts at 0. Negative numbers count from the end: -1 is the last character.
| Character | W | i | c | k |
|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 |
| From the end | -4 | -3 | -2 | -1 |
1name = "Wick"2print(name[0])3print(name[3])4print(name[-1])5print(name[4])
W
k
k
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(name[4])
IndexError: string index out of range"Wick" has 4 characters, so the last index is 3. Asking for name[4] is an IndexError. To get the last character of any string, [-1] is easier than working out the length.
Slicing
text[start:stop] takes a piece of a string: from start up to, but not including, stop. Leave out start to begin at the front; leave out stop to go to the end.
1word = "lamplighter"2print(word[0:4])3print(word[4:9])4print(word[:4])5print(word[4:])6print(word[-3:])
lamp light lamp lighter ter
A handy way to think of it: the numbers point at the gaps between characters. [0:4] cuts at gap 0 and gap 4, which leaves 4 characters. And word[:4] + word[4:] always gives back the whole word.
What does this print?
1word = "sunrise"2print(word[1:4])
It starts at index 1 (u) and stops before index 4, so you get indexes 1, 2 and 3: unr.
Unlike a single index, a slice never gives an error. If it runs past the end, you simply get less, or an empty string.
Steps and reversing
A third number sets the step: [::2] takes every second character. A step of -1 walks backwards, which reverses the string.
1digits = "0123456789"2print(digits[::2])3print(digits[1::2])4print("stressed"[::-1])
02468 13579 desserts
[::-1] is the usual Python way to reverse a string. Read it as "the whole thing, backwards".
Strings can't be changed
You can read any character of a string, but you cannot replace one in place:
1name = "Wick"2name[0] = "N"
Traceback (most recent call last):
File "main.py", line 2, in <module>
name[0] = "N"
TypeError: 'str' object does not support item assignmentStrings are immutable: once made, they stay as they are. To "change" one, build a new string from pieces and store it under the same name:
1name = "Wick"2name = "N" + name[1:]3print(name)
Nick
Special characters and long text
The backslash codes from lesson 1 work in every string: \n for a new line, \t for a tab, \" for a quote. A \n counts as one character. For text that spans several lines, three quotes are easier: everything up to the closing three quotes is kept, line breaks and spaces included.
1print(len("a\nb"))2sign = """Lamp Street3 No. 7"""4print(sign)
3 Lamp Street No. 7
Tip: Strings in triple quotes are also how Python programmers write longer notes at the top of a program. You will see them again with functions.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Initials
✓Use indexing to print the initials of first and last, each followed by a period.
A.L.
1first = "Ada"2last = "Lovelace"3print(first, last)
Backwards
✓Print word reversed. You get a different word.
reward
1word = "drawer"2print(word)
Card ending
✓Show only the last four digits of the card number, in the sentence below.
Card ending in 3316
1card = "4921 7734 0058 3316"2print("Card ending in", card)
What you learned
+joins strings,*repeats them; numbers must be converted first.len()counts characters;""is the empty string.text[0]is the first character,text[-1]the last; past the end is anIndexError.text[start:stop]slices up to but not includingstop; either end can be left out.text[::-1]reverses a string.- Strings are immutable: build a new one instead of changing a character.
- Triple quotes make a string that spans several lines.