Lesson 6 of 35Python
Python · Lesson 6 · 25 minutes
Working with strings
What you'll learn
- Cut out single letters and pieces of text
- Change text with
upper(),lower()andreplace() - Count letters with a loop
Strings are chains of characters
A piece of text (in Python it’s called a string, type str) is a chain of single characters. Almost everything you learned about lists works here too:
name = "Python"
print(len(name))
print(name[0])
print(name[-1])Cutting out pieces (slicing)
With [start:end] you cut out a piece. The character at position end is not included any more:
word = "chocolate"
print(word[0:5])
print(word[5:])
print(word[::-1])| Notation | Meaning |
|---|---|
word[0:5] | characters 0 to 4 |
word[5:] | from character 5 to the end |
word[:3] | the first 3 characters |
word[::-1] | everything backwards |
Changing text
Strings have many built-in methods. You call them with a dot. The original text stays unchanged – you get a new text back:
sentence = "I like maths."
print(sentence.upper())
print(sentence.lower())
print(sentence.replace("maths", "coding"))
print(sentence.split(" "))
print(sentence)split() breaks a text into a list. That’s great when someone types several words at once.
Character by character
With for you go through every letter one by one. Here we count how often an “e” appears:
text = "The elephant eats"
count = 0
for char in text.lower():
if char == "e":
count = count + 1
print(f"There are {count} e's.")Tip: There’s also a shortcut for exactly this:
text.lower().count("e"). But it’s good to know how it works with a loop.
Quick check
Before you start the task: what does this program print? Type your guess – then Python works it out.
word = "Python"
print(word[0], word[-1], word[1:3])Your task
Your turn
Ask for a word with input(). Then print three lines, for example for “Robot”: Backwards: toboR, Capitals: ROBOT and Vowels: 2. Count the vowels a, e, i, o and u – no matter whether they are upper or lower case.
word = input("Enter a word: ")
# Your output:- Something to think about
word[::-1]gives you the text backwards. - Which command helps?
Go through every letter with
forand check with in"aeiou"whether it's a vowel.The capital A isn't counted. Turn the word into lower case with
lower()first. - Gap code – fill in the ___
word = input("Enter a word: ") print(___) print(___) vowels = ___ for letter in ___: if ___: vowels = ___ print(___)
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
word = input("Enter a word: ")
print(f"Backwards: {word[::-1]}")
print(f"Capitals: {word.upper()}")
vowels = 0
for letter in word.lower():
if letter in "aeiou":
vowels = vowels + 1
print(f"Vowels: {vowels}")