Strings
A string is a piece of text: a name, a sentence, a password, a whole file. Strings are one of the types you'll use most. In this lesson you'll learn how to build strings and pick out parts of them. The next lesson covers the many built-in tools for changing them.
Creating strings
Put text inside single or double quotes. For text that spans several lines, use triple quotes:
first = "Hello" second = 'World' poem = """Roses are red, Violets are blue, Python is fun, And so are you.""" print(first, second) print(poem)
Triple quotes can be """ or '''. The line breaks you type inside them become part of the string, so poem prints on four lines.
A string can also be empty: "" is a string with no characters in it. It's useful as a starting value that you add to later.
Joining and repeating
+ joins strings end to end, and * repeats a string:
first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("ha" * 3)
print("-" * 20)Notice the " " in the middle: + doesn't add spaces for you. Without it you'd get AdaLovelace.
Both operators have rules about what they work with:
| Expression | Result | Why |
|---|---|---|
"ab" + "cd" |
"abcd" |
+ joins two strings |
"ab" * 3 |
"ababab" |
* repeats a string a whole number of times |
"Age: " + 30 |
TypeError |
+ can't join a string and a number |
"Age: " + str(30) |
"Age: 30" |
convert the number to a string first |
Counting characters with len()
len() tells you how many characters a string has. Spaces and punctuation count too:
print(len("Python"))
print(len("Hello, World!"))
print(len("")) # empty string: 0Indexing: getting one character
Each character in a string has a numbered position called an index. Python starts counting at 0, not 1, so the first character is at index 0. Negative indexes count backwards from the end:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Put the index in square brackets after the string:
Predict first: using the diagram above, what will each line print?
word = "Python" print(word[0]) print(word[3]) print(word[-1]) print(word[-2])
word[0] is always the first character and word[-1] is always the last, however long the string is.
Because counting starts at 0, the last index is always one less than the length. "Python" has 6 characters, so its indexes run from 0 to 5. Asking for a position that doesn't exist raises an IndexError:
word = "Python" print(word[10])
Slicing: getting part of a string
A slice gives you a piece of a string. word[start:end] takes the characters from start up to, but not including, end:
word = "Python" print(word[0:2]) # positions 0 and 1 print(word[2:5]) # positions 2, 3 and 4
end is left out for the same reason as with range() later on: it makes the arithmetic easy. end - start is the number of characters you get, so word[2:5] gives 5 - 2 = 3 characters: tho.
Leave out start to begin at the start, or end to go all the way to the end:
word = "Python" print(word[:3]) # the first 3 characters print(word[3:]) # from position 3 on print(word[-3:]) # the last 3 characters
Here are the patterns you'll use most, for word = "Python":
| Slice | Means | Result |
|---|---|---|
word[1:4] |
positions 1, 2 and 3 | yth |
word[:3] |
the first 3 characters | Pyt |
word[3:] |
everything from position 3 to the end | hon |
word[-3:] |
the last 3 characters | hon |
word[:-1] |
everything except the last character | Pytho |
word[:] |
the whole string | Python |
Unlike indexing, slicing never raises an IndexError. If the numbers go past the end, you just get whatever characters exist, or an empty string:
word = "Python" print(word[2:100]) print(word[10:20]) print(len(word[10:20]))
Reversing a string
One more pattern is worth memorising: word[::-1] gives the string reversed.
print("Python"[::-1])
print("stressed"[::-1])Going deeper: How [::-1] works: the step optional
A slice can take a third number, the step, which says how far to jump each time: word[start:end:step]. A step of 2 takes every second character, and a negative step walks backwards, so [::-1] means "the whole string, backwards one character at a time".
word = "Python" # every second character print(word[::2]) # every second, from position 1 print(word[1::2]) # backwards print(word[::-1]) # backwards, every second one print(word[::-2])
Strings can't be changed
Once a string is created, you can't change a single character inside it:
word = "Python" word[0] = "J"
That's a TypeError: Python won't let you assign to a position inside a string.
Instead, build a new string from the pieces you want:
word = "Python" new_word = "J" + word[1:] print(new_word)
Programmers say strings are immutable, which just means "can't be changed in place".
Special characters
A backslash \ inside a string starts a special character. You met these in the first lesson; here they are again for reference. Each one counts as one character, so len("a\nb") is 3:
| Write | To get |
|---|---|
\n |
a new line |
\t |
a tab (a wide space) |
\" |
a double quote inside double quotes |
\' |
a single quote inside single quotes |
\\ |
a backslash |
print("Line one\nLine two")
print("Name:\tAda")
print("She said \"hi\"")
print("C:\\Users\\Ada")Going deeper: Raw strings: when backslashes get in the way optional
Windows file paths are full of backslashes, and some of them accidentally form special characters. Here \n in \new becomes a new line:
print("C:\new_folder\notes.txt")Put an r before the opening quote to make a raw string. In a raw string, a backslash is just a backslash:
print(r"C:\new_folder\notes.txt")
Raw strings are also common in regular expressions, a mini-language for searching text that uses lots of backslashes.
Exercises
Exercise 1: Initials
Print the initials of the name below, followed by full stops: A.L.
first_name = "Ada" last_name = "Lovelace"
first_name[0] gives the first letter of a string.
Join four pieces with +: the first initial, ".", the second initial and ".".
Exercise 2: The middle part
Use a slice to print just yth from the word.
word = "Python"
y is at position 1 and h is at position 3.
The end of a slice is not included, so the slice must end one position after h: word[1:4].
Exercise 3: Underline a title
Print the title, and underneath it a line of = signs exactly as long as the title:
Shopping list
=============
title = "Shopping list"
len(title) tells you how many characters the title has.
Repeat the = sign that many times with *: "=" * len(title).
Exercise 4: Palindrome check
A palindrome reads the same forwards and backwards. Print True if word is a palindrome.
word = "racecar"
word[::-1] gives the word reversed.
Compare the word with its reverse using ==.
String operations at a glance
A quick reference for later. Each example starts from s = "Python". Results are shown with quotes, so you can see exactly where each string starts and ends.
| Operation | What it does | Example | Result |
|---|---|---|---|
s[i] |
The character at position i (counting from 0) |
s[0] |
'P' |
s[-i] |
Counts from the end: -1 is the last character |
s[-1] |
'n' |
s[start:end] |
A slice, from start up to (not including) end |
s[1:4] |
'yth' |
s[:n] |
The first n characters |
s[:2] |
'Py' |
s[-n:] |
The last n characters |
s[-3:] |
'hon' |
s[::-1] |
The string reversed | s[::-1] |
'nohtyP' |
s + other |
Joins two strings | s + "!" |
'Python!' |
s * n |
Repeats the string n times |
s * 2 |
'PythonPython' |
len(s) |
Number of characters | len(s) |
6 |
x in s |
Does x appear inside s? |
"th" in s |
True |
str(x) |
Turns a value into a string | str(42) |
'42' |
Strings also have dozens of built-in methods, such as upper() and replace(). They're the topic of the next lesson, String Methods.
Summary
- Strings are text in quotes. Use triple quotes for text over several lines.
+joins strings,*repeats them, andlen()counts characters.- Indexes start at 0:
s[0]is the first character ands[-1]the last. s[start:end]slices out a piece. The end is not included.s[:3]gives the first 3 characters,s[-3:]the last 3, ands[::-1]reverses.- Strings can't be changed in place. Build a new string instead.
\nstarts a new line, and\tadds a tab.
Know something worth teaching? Write your own tutorial with runnable examples and share it.