< previous | Table of Contents | next > |
6.5 LOOPING OVER STRINGS
Often, when working with strings, we need to iterate over them to conduct operations. For loops come in handy for that purpose.
USING A FOR LOOP
The most straightforward way to loop over a string is by using a for
loop. You can think of a string as a sequence of characters, each of which you can access and iterate over sequentially using a for loop.
for character in "Prisoner of Azkaban": print(character)
This loop will print each character of the string "Prisoner of Azkaban" on a new line.
ACCESSING CHARACTERS BY THEIR INDEX
You can also loop over a string by its index using a for loop combined with the range()
function and the len()
function. This method provides you with the index of each character, which can be useful for tasks that require knowledge of the character's position in the string.
text = "Prisoner of Azkaban" for index in range(len(text)): print(index)
USING ENUMERATE
The enumerate()
function returns both the character and the index of the character. It’s a clean way of accessing both at once.
for index, character in enumerate("Harry Potter"): print("Index: ", index, ". Character: ", character)
This prints out the index and the corresponding character.
LOOPING WITH CONDITIONS
You can combine looping over a string with conditionals to perform more complex tasks, such as counting occurrences of a certain character or group of characters.
count = 0 for character in "Harry Potter and the Prisoner of Azkaban": if character.isupper(): count += 1 print(count)
This loop counts all the uppercase characters in the provided string.
MODIFYING STRINGS IN A LOOP
Since strings in Python are immutable, you cannot modify them directly in a loop. However, you can construct a new string.
initial_string = "Harry Potter and the Prisoner of Azkaban" new_string = "" for character in initial_string: if character.islower(): new_string += character print(new_string)
This loops creates a new string and adds all the lowercase characters of the initial string.
KEY THINGS TO REMEMBER
- Strings can be directly iterated over with a
for
loop. - Combining
range()
andlen()
functions,for
loops can iterate over strings by their index. enumerate()
provides a way to get both the index and the character in the string during iteration.- While strings are immutable, we can create a new string and add elements as desired to it.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |