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)
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.
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("")) # an empty string has length 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.
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
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:]) # everything from position 3 on print(word[-3:]) # the last 3 characters
Tip:
word[:3]means "the first 3 characters" andword[-3:]means "the last 3 characters". These two patterns cover most everyday slicing.
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" print(word[::2]) # every second character print(word[1::2]) # every second character, starting at position 1 print(word[::-1]) # backwards print(word[::-2]) # backwards, every second character
Strings can't be changed
Once a string is created, you can't change a single character inside it:
word = "Python" word[0] = "J"
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 \n (new line) in the first lesson. Here are the common ones:
| 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.