Lesson 3 of 12 · about 15 minutes
Working with text
Strings are everywhere
Names, messages, answers to questions: most programs handle a lot of text. In Python, text is a string (str), written inside quotes.
city = "Kathmandu"
print(city)Joining strings
The + operator joins two strings into one. This is called concatenation. It does not add spaces for you:
first = "Ada"
last = "Lovelace"
print(first + last)
print(first + " " + last)AdaLovelace
Ada Lovelace+ only joins strings with strings. "Age: " + 12 causes a TypeError. You can convert a number to a string with str(12), but there is an easier way.
f-strings
Put the letter f before the opening quote and you can drop variables straight into the text using curly brackets:
name = "Sam"
age = 12
print(f"{name} is {age} years old")
print(f"Next year {name} will be {age + 1}")Sam is 12 years old
Next year Sam will be 13Anything inside the curly brackets is worked out first, so you can do sums there too. f-strings are the most common way to build messages in Python.
Quick check
What does this print?
name = "Mia"
print(f"Hi {name}!")String methods
Strings come with built-in tools called methods. You call a method by putting a dot after the string:
word = "python"
print(word.upper())
print(word.capitalize())
print(" hello ".strip())
print("I like cats".replace("cats", "dogs"))PYTHON
Python
hello
I like dogsMethods give you a new string. They do not change the original, so word is still "python" afterwards.
Length and letters
len tells you how many characters a string has, spaces included:
print(len("Hello"))5Each character has a position, called its index. Counting starts at 0, not 1. Square brackets pick out a character:
word = "Python"
print(word[0])
print(word[1])
print(word[-1])P
y
nA negative index counts from the end, so word[-1] is the last character. You can also take a slice: word[0:3] gives the characters at positions 0, 1 and 2, which is "Pyt".
Quick check
What does this print?
word = "Python"
print(word[1])Exercise 1: A proper greeting
The names are stored in lowercase. Use them to print Hello, Ada Lovelace! with capital letters, using the first and last variables rather than typing the name yourself.
Exercise 2: Initials
Print the initials of the name in capital letters: GBH. Pick the letters out of the name variable using their index.
Lesson 3 complete
You finished working with text and passed every exercise.
What you learned
+joins strings; it does not add spaces.- f-strings like
f"Hi {name}"put values into text. - Methods such as
.upper(),.capitalize()and.replace()return a new string. len(text)counts characters, andtext[0]is the first one.
Next up: Asking for input. It is coming soon.
Back to the course