Learn Python · lesson 22 of 60 · about 8 minutes
enumerate() and Building Strings
List which nights were short: loop with both position and value, and build up new text inside a loop.
What you'll learn
- Use enumerate() to get index and value
- Build a string inside a loop
- Reverse or filter text
Which nights?
Knowing how many nights were good isn't the whole story. Sam wants to know which nights were short: Short nights: 1, 5, 6, 7. For that the loop needs each night's number as well as its hours, and it has to build the line a piece at a time, with a comma between the numbers but not before the first one.
Position and value together
enumerate() gives you two things each time round: the index and the item. Write two names after for, separated by a comma.
Numbered letters
for i, letter in enumerate("code"):
print(i, letter)Output
0 c
1 o
2 d
3 eBuilding new text
Start with an empty string "" and add to it inside the loop. Adding to the front instead of the back reverses the text.
Remove vowels, and reverse
word = "python"
no_vowels = ""
backwards = ""
for ch in word:
if ch not in "aeiou":
no_vowels += ch
backwards = ch + backwards
print(no_vowels)
print(backwards)Output
pythn
nohtypStep through it: commas only between numbers
short = ""
for number, hours in enumerate("659", start=1):
if int(hours) < 7:
if short != "":
short += ", "
short += str(number)
print(short)Output
1, 2Tip
+= only adds text to text. The night's number is an int, so str(number) turns it into text before it's added to short.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.