Python · Lesson 1.3
Strings
Text in Python: quotes, joining, length, and picking out single characters.
1Text goes in quotes
A string is text inside quotes. Single and double quotes both work; pick the one that isn't inside your text.
name = "Priya" note = "It's raining" print(name, note)
Practice
Store the text Don't forget the receipt in a variable called reminder and print it.
# Create reminder and print it
2Join and repeat
+ glues strings together and * repeats one. Neither adds spaces for you.
first = "data"
second = "science"
print(first + " " + second)
print("-" * 20)Practice
Build the email address ana.silva@shop.example from the two variables below with +, and print it.
first = "ana" last = "silva" # Build and print the email address
3Length and single characters
len() counts the characters. Square brackets pick one character by position, and counting starts at 0; -1 is the last one.
code = "SKU-4821" print(len(code)) print(code[0], code[4], code[-1])
Common mistake
The first character is [0], not [1]. And code[len(code)] is one past the end, so it raises an IndexError.
Practice
Print the first letter of product, then on the next line its last letter, then on a third line its length.
product = "notebook" # Print first letter, last letter, length
4Special characters
A backslash starts a special character: \n is a new line and \t is a tab. A string in triple quotes can span several lines.
print("Name\tScore")
print("Ana\t91\nBen\t78")Practice
Print this two-line receipt using one print() and \n:
Item: tea
Price: 3
# One print() with \n