A string is a piece of text. You can write it with double quotes or single quotes, as long as both ends match:
first = "Ada"
last = 'Lovelace'
Joining strings
The + operator glues strings together. You add the spaces yourself:
full = first + " " + last # "Ada Lovelace"
Joining only works between strings. "Age: " + 36 is an error, because 36 is a number.
f-strings
The easy way to mix text and values is an f-string. Put the letter f right before the opening quote. Then anything inside curly braces is replaced by its value:
age = 36
print(f"{first} is {age} years old.")
print(f"Next year: {age + 1}")
Numbers, variables and whole calculations can all go in the braces.
Length and methods
len() tells you how many characters a string has:
print(len(first)) # 3
Strings also come with built-in tools called methods. You call a method with a dot after the string:
| Method | Result for "Hello" |
|---|---|
.upper() | "HELLO" |
.lower() | "hello" |
.replace("H", "J") | "Jello" |
.strip() | removes spaces at both ends |
.startswith("He") | True |
A method gives back a new string. The original is never changed.
A number in quotes is a string: "5" + "5" is "55", not 10.
Your Task
- Create a variable
greetingwith an f-string, so that it holds exactlyWelcome to Paris, Mia!built from the two variables. - Print
greeting. - Print the city name in capital letters, using a method.
- Print the number of characters in
name.
greetingis exactlyWelcome to Paris, Mia!- It is built with an f-string that uses both variables
- The greeting is printed
PARISis printed, made withupper()- The length of the name,
3, is printed