str basics
- Python course
- Beginner
- Lesson 15/116
- 4 min
Learn text and escape sequences with str.
str basics
str (string) is the text type. Strings are written in single or double quotes:
name = "Alex"
city = 'London'Both quote styles are the same; which one you pick is a style choice. To use the same quote inside, escape it: "O\"clock" or use the other quote: 'O"clock'.
For long text use triple quotes: """multi-line""".
Escape sequences
For special characters inside a string use escape sequences. \n is a new line, \t is a tab, \\ is a backslash:
print("Line 1\nLine 2")To use the same quote inside, use \" or \'. Escape sequences are part of the quoted string. A raw string with an r prefix turns off escape sequences.
Practice Print a string
Assign "Alex" to name. Then print it with print(name).
Starter code
# Define the stringSample solution
name = "Alex"
print(name)Expected output
Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid str assignment?
- name = "Alex" Correct answer
- name = Alex
- name = 'Alex"
- name = (Alex)
Explanation: name = "Alex" is a double-quoted str assignment.
2 Add a new line
print("Line 1____Line 2")
print("Line 1\nLine 2")
Explanation: \n is the new line escape sequence.
3 Match the str concepts
| Term | Meaning |
|---|---|
str |
Text type |
\n |
New line |
"Alex" |
Double-quoted string |
'Alex' |
Single-quoted string |