Python Strings for Beginners: Join, Repeat and f-strings
What Is a String?
You've used strings since chapter 2. Now let's look at them properly. A string (str) is a sequence of characters inside quotes: letters, digits, spaces and symbols.
Think of a string as a necklace of beads. Each character is one bead, in a fixed order. "Hi!" is three beads: H, i and !.
greeting = "Hello, Sunny!"
print(greeting)
print(type(greeting))Hello, Sunny! <class 'str'>
What you already know
- Single or double quotes both work; start and end with the same one.
- Triple quotes let a string go over several lines.
- Escape sequences like
\nand\twork inside any string.
Everything in quotes is text
Digits in quotes are text too, so Python won't do maths with them:
age_text = "25"
age_number = 25
print(type(age_text), type(age_number))<class 'str'> <class 'int'>
The empty string
A string can have zero characters: "". It's still a string, just an empty one. You'll use it as a starting value, like an empty box waiting to be filled.
nickname = ""
print("Nickname:", nickname, "(none yet)")Nickname: (none yet)
Notice the two spaces in the output: one before the empty string and one after it.
A string is a necklace of characters inside quotes, even digits and spaces.