A string (str) is a sequence of characters. Almost everything a program shows is text, so it is worth mastering how to create it, how to access its letters and how to extract pieces of it.
Creating strings
They are written between single or double quotes, it makes no difference. With three quotes you can write several lines:
a = 'Hello'
b = "Hello"
c = """First line
second line"""
print(c)
# First line
# second line
Special characters
The backslash \ introduces special sequences inside the text:
| Sequence | Meaning | Example |
|---|---|---|
\n | New line | print("Line 1\nLine 2") |
\t | Tab | print("a\tb") |
\" | Double quotes inside the text | print("He said: \"hi\"") |
\\ | A backslash | print("C:\\data") |
Indexes: the position of each character
Each character has a position, which starts at 0 (not 1). Negative indexes count from the end:
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
word = "Python"
print(word[0]) # P
print(word[2]) # t
print(word[-1]) # n (the last one)
print(len(word)) # 6 (how many characters)
If you ask for a position that does not exist, Python raises an IndexError (string index out of range).
Slices
text[start:end] returns a piece: it starts at start and goes up to end, not including it. If you omit one of them, the beginning or the end is used:
word = "Python"
print(word[1:4]) # yth
print(word[:3]) # Pyt (from the beginning)
print(word[3:]) # hon (to the end)
print(word[-3:]) # hon (the last three)
A third number sets the step. With step -1 it goes backwards, which is the shortest way to reverse a text:
print(word[::2]) # Pto (every other letter)
print(word[::-1]) # nohtyP
Searching inside a text
The in operator checks whether a piece appears inside the string and returns True or False:
print("yth" in word) # True
print("xyz" in word) # False
Joining and repeating
print("Hello" + " " + "world") # Hello world
print("ab" * 3) # ababab
Common mistake: changing a letter
Strings are immutable: you cannot change a letter in place. You have to create a new string:
word[0] = "p"
# TypeError: 'str' object does not support item assignment
word = "p" + word[1:] # correct: creates a new string
print(word) # python
Practice in the exercises about reversing characters, initials and slices of a word.