Python Basics · Lesson 4 of 12

Strings

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:

MethodResult 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

  1. Create a variable greeting with an f-string, so that it holds exactly Welcome to Paris, Mia! built from the two variables.
  2. Print greeting.
  3. Print the city name in capital letters, using a method.
  4. Print the number of characters in name.
  • greeting is exactly Welcome to Paris, Mia!
  • It is built with an f-string that uses both variables
  • The greeting is printed
  • PARIS is printed, made with upper()
  • The length of the name, 3, is printed