Working with strings
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Letters have positions
- A string is a row of characters.
- Each character has a position, called an index.
- Indexes start at
0. Uses[-1]for the last character.
word = "Python"
print(word[0])
print(word[-1])
Take a slice
- A slice takes part of a string:
s[start:end]. - The character at
endis not included. - Leave a side empty for "from the start" or "to the end":
s[:3],s[2:].
msg = "hello"
print(msg[:3])
print(msg[2:])
Length and changing case
len(s)gives the number of characters.s.upper()makes a CAPITAL copy;s.lower()makes a lowercase copy.- These make a new string; the original does not change.
city = "Tokyo"
print(len(city))
print(city.upper())
print(city.lower())
f-strings build text
- An f-string starts with
fbefore the quote. - Put a value inside
{ }and Python drops it into the text. - It is the neat way to mix words and values.
fruit = "apple"
count = 3
print(f"I have {count} {fruit}s")
Now you try
- Read the task to see which variable to fill or what to print.
- Press Check answer to test your code.
word is "computer". Store its first character in first, and its first four characters in first_four, using indexing and a slice.
Click Run to see the output here.
phrase is "Hello World". Store its length in n with len(...), and an UPPERCASE copy in loud with .upper().
Click Run to see the output here.
name is "Mia" and age is 12. Use an f-string to print exactly: Mia is 12 years old.
Click Run to see the output here.