Python Strings
What you will learn
- What a string is and how to write one with single, double and triple quotes
- Escape sequences such as
\nand\t, and raw strings len,+and*with text- How Python compares and orders strings
inandnot in, and the first errors you will meet
1. What is a string?
A string (type str) is a piece of text: a sequence of characters, such as letters, digits, spaces and symbols. You write one inside quotation marks:
a = 'single'
b = "double"
print(a, b, type(a), len(a))
single double <class 'str'> 6
Single and double quotes work exactly the same. Pick one style and stay with it. Use the other kind when the text itself contains a quote:
print("It's fine")
print('He said "hi"')
It's fine
He said "hi"
The empty string "" has no characters, and its length is 0.
Quick check: how do you write the text `Don't` without a backslash?
Put it in double quotes: "Don't".
2. Multi-line strings with triple quotes
Three quotes in a row, """ or ''', let the text continue over several lines. The line breaks are kept:
s = """Line one
Line two
indented"""
print(s)
print(repr(s))
Line one
Line two
indented
'Line one\nLine two\n indented'
repr() shows the string the way you would write it in code, with \n for each line break. Inside triple quotes you can freely use single and double quotes: '''She said "it's fine".'''.
To continue a long line of code (not a line break in the text), put a backslash at the end of the line, or use brackets and write the pieces side by side. Neighbouring string pieces are joined automatically:
long = ("one "
"two "
"three")
print(long)
one two three
3. Escape sequences
A backslash \ inside a string starts a special character:
| Code | Meaning |
|---|---|
\n |
new line |
\t |
tab |
\\ |
one backslash |
\' |
a single quote |
\" |
a double quote |
\u00e9 |
the character with that Unicode number (here é) |
print("tab\there")
print("back\\slash")
print("a\nb", len("a\nb"))
tab here
back\slash
a
b 3
Notice that "a\nb" has three characters: a, the new line and b. The two keystrokes \n are one character. Unicode escapes are explained in lesson 4.8.
4. Raw strings
Sometimes backslashes should be ordinary characters, as in Windows file paths or patterns. Put an r in front of the quotes to make a raw string:
print(r"C:\new\table")
print(len(r"C:\new"), len("C:\\new"))
C:\new\table
6 6
In a normal string, "C:\new" would turn \n into a new line. The raw string keeps all six characters (C, :, \, n, e, w). Writing the backslash twice in a normal string, "C:\\new", gives the same six characters, so both lengths are 6. A raw string cannot end with a single backslash. Raw strings are very common for regular-expression patterns (lesson 17.6).
5. Length, joining and repeating
print(len("hello"), len(""))
print("a" + "b", "ab" * 3, "-" * 10)
print("ab" + str(5))
5 0
ab ababab ----------
ab5
| Operation | Meaning |
|---|---|
len(s) |
the number of characters |
s + t |
joins two strings |
s * n |
repeats s, n times (0 or less gives "") |
You can only join text to text. Convert numbers with str() (lesson 2.4):
"5" + 5
TypeError: can only concatenate str (not "int") to str
A string can be multiplied only by a whole number:
"ab" * 2.0
TypeError: can't multiply sequence by non-int of type 'float'
Remember that "5" + "5" is "55" and "5" * 3 is "555", while int("5") * 3 is 15.
6. Comparing strings
== checks whether two strings are identical, character for character. It is case-sensitive:
print("apple" == "apple", "apple" == "Apple")
True False
< and > compare strings in dictionary-like order, but by the code number of each character, not true alphabetical rules. Every character has a number, shown by ord(), and chr() goes back:
print(ord("a"), ord("A"), chr(97), chr(8364))
print("apple" < "banana", "Zebra" < "apple", "a" < "B")
print("10" < "9")
97 65 a €
True True False
True
- Capital letters come before all lower-case letters, so
"Zebra" < "apple"isTrue. - Strings of digits are compared character by character, not as numbers, so
"10" < "9"isTrue(because"1"comes before"9").
To compare ignoring case, change both to the same case first: a.lower() == b.lower(). Lesson 4.3 covers the methods.
7. Testing for text inside text: in
in asks whether one string is part of another:
print("py" in "python", "PY" in "python")
print("x" not in "abc", "" in "abc")
True False
True True
The empty string is inside every string. Case matters: "PY" is not found in "python".
8. Strings and truth
An empty string counts as false, and any other string as true (lesson 2.3):
print(bool(""), bool(" "), bool("0"))
False True True
9. Looking at a string
For a quick look, print(s) shows the text as a reader would see it, and repr(s) shows it as code, with quotes and escapes. When something looks wrong, such as a hidden space or line break, try print(repr(s)).
Worked example: a three-line label
Make a label with a name, a line of dashes the same length as the name, and a tab-separated price.
name = "Notebook"
line = "-" * len(name)
label = name + "\n" + line + "\nPrice:\t5"
print(label)
Notebook
--------
Price: 5
| Step | What it does |
|---|---|
len(name) |
counts the 8 letters |
"-" * 8 |
makes 8 dashes |
"\n" |
starts a new line |
"\t" |
adds a tab |
The name and price are made up for the example.
Common mistakes
- Mixing text and numbers with
+. Usestr(5)or an f-string. - Forgetting that
\nis one character, and counting it as two. - Writing a Windows path in a normal string (
"C:\new"): use a raw string,r"C:\new". - Comparing numbers stored as text (
"10" < "9"isTrue). Convert them first. - Expecting
==to ignore case. - Starting with one kind of quote and ending with the other.
Key takeaways
- A
stris text; single and double quotes are the same, and triple quotes allow several lines. - A backslash starts an escape:
\n,\t,\\,\',\". A raw stringr"..."ignores them. lencounts characters,+joins,*repeats; you can only join text to text.==is case-sensitive;<compares characters by their code numbers (capitals first).intests whether text appears inside other text.
Practice
1. Write a string containing the text She said "hello" in two different ways.
Show answer
'She said "hello"' (single quotes outside) or "She said \"hello\"" (escaped double quotes).
2. What is len("a\tb")?
Show answer
3: the letter a, one tab character and the letter b.
3. What does "ha" * 3 + "!" give?
Show answer
"hahaha!".
4. Why does "Zebra" < "apple" give True?
Show answer
Strings are compared by character code numbers, and capital letters have smaller numbers than lower-case letters (ord("Z") is 90 and ord("a") is 97).
5. Write a raw string for the path D:\data\new, and say why a normal string would fail.
Show answer
r"D:\data\new". In a normal string, \n would become a new line, and \d is not a recognised escape (Python warns about it).
6. What do "cat" in "concatenate" and "Cat" in "concatenate" give?
Show answer
True and False. The search is case-sensitive.