Strings as lists
Although they may not look the same, in Python we can treat strings in a very similar way to lists. In Python terms, they are both “iterables”. This means that, in much the same way as we can use a
for loop to repeat an action for each element in a list, we can do the same for each character in a string:
my_list = ['apple', 'banana', 'pear'] my_string = 'fig' for item in my_list: print(item) for item in my_string: print(item)
The code inside each of these loops will run three times, as the list has three elements, and the string has three characters.
We can also access characters in strings in the same way as elements in lists, using indices inside square brackets. For example, for the string
topic = "algorithms",
topic would refer to the first character, which in this case is
topic would give
topic would give
"g", and so on. As with lists, you can use negative numbers to count back from the end of the list:
topic[-1] would give
topic[-5] would give
Slicing strings also works in the same way as slicing lists. Try out the following code:
topic = "slicing strings" print(topic[:3]) print(topic[5:]) print(topic[2:12])
What strings are printed in each case?
Check that you are happy with how this works. The number before the colon gives the index of the first character in the slice, while the number after the colon gives the index of the first character which will not be included in the slice. Also, the space between the two words counts as a character, and in this string its location gives an index of 7.
Here is an example of a list of team names:
teams = ["WOLVES", "OWLS", "PANTHERS", "BEARS", "DRAGONS"]
On scoreboards, sports teams are sometimes referred to using a contraction of their name, often the first three letters. Can you write some code in order to create a new list,
teams_short, containing three-letter contractions of each of the teams in the list, in the same order as they appear in
Share your code, problems, and suggestions in the comments.