Python Strings
A string (str) is a sequence of characters — letters, digits, spaces, emoji, anything. Python strings are Unicode, so text in any language just works.
Creating strings
Use single or double quotes; they mean exactly the same thing. Pick whichever avoids escaping:
a = 'single quotes'
b = "double quotes"
c = "It's easy"
d = 'He said "wow"'
print(a, b, c, d, sep="\n")single quotes
double quotes
It's easy
He said "wow"
Triple quotes (""" or ''') create a multi-line string; the line breaks are kept:
poem = """Roses are red,
Python is neat,
Indentation matters,
And so does the beat."""
print(poem)Roses are red,
Python is neat,
Indentation matters,
And so does the beat.
Strings are sequences
Each character has a position called an index, starting at 0. Negative indexes count from the end:
| Character | P |
y |
t |
h |
o |
n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative | -6 | -5 | -4 | -3 | -2 | -1 |
word = "Python"
print(word[0])
print(word[-1])
print(len(word))
for ch in "abc":
print(ch.upper())P
n
6
A
B
C
Slicing
text[start:end] extracts a substring from start up to — but not including — end. Either side can be left out, and a third value sets the step:
s = "Hello, World"
print(s[0:5]) # first five characters
print(s[7:]) # from index 7 to the end
print(s[:5]) # same as s[0:5]
print(s[-5:]) # last five characters
print(s[::2]) # every second character
print(s[::-1]) # reversedHello
World
Hello
World
Hlo ol
dlroW ,olleH
Strings are immutable
You can't change a character in place. Build a new string instead:
name = "jython"
try:
name[0] = "P"
except TypeError as err:
print("Error:", err)
name = "P" + name[1:]
print(name)Error: 'str' object does not support item assignment
Python
Combining and repeating
| Operation | Example | Result |
|---|---|---|
| Concatenate | "ab" + "cd" |
"abcd" |
| Repeat | "ha" * 3 |
"hahaha" |
| Membership | "or" in "World" |
True |
| Not in | "x" not in "abc" |
True |
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
print("-" * 12)
print("Love" in full)
print("love" in full) # checks are case-sensitiveAda Lovelace
------------
True
False
Tip: For gluing many pieces together,
" ".join(pieces)is faster and cleaner than repeated+. It's covered in String Methods.
Raw strings
Put r in front of a string to turn off escape sequences. This is handy for Windows paths and regular expressions:
print("C:\new\table")
print(r"C:\new\table")C:
ew able
C:\new\table
In the first line, \n became a new line and \t a tab!
Test yourself
What is "Python"[1:4]?
- "Pyt"
- "yth"
- "ytho"
- "thon"
What does "abc"[-1] return?
- "a"
- "c"
- An IndexError
- ""
Why does s[0] = "X" fail for a string s?
- Strings are immutable
- Index 0 is reserved
- You must use s.set(0, "X")
- It only fails for empty strings