Книга: Practical Programming, Fourth Edition
Назад: Processing Items in a List
Дальше: Looping Over a Range of Numbers

Processing Characters in Strings

It is also possible to loop over the characters of a string. The general form of a for loop over a string is as follows:

​ ​for​ variable ​in​ str:
​  body

As with a for loop over a list, the loop variable gets assigned a new value at the beginning of each iteration. In the case of a loop over a string, the variable is assigned a single character at a time.

For example, you can loop over each character in a string, printing the uppercase letters:

​ ​>>>​​ ​​country​​ ​​=​​ ​​'United States of America'​
​ ​>>>​​ ​​for​​ ​​ch​​ ​​in​​ ​​country:​
​ ​...​​ ​​if​​ ​​ch.isupper():​
​ ​...​​ ​​print(ch)​
​ ​...​
​ U
​ S
​ A

In the previous code, variable ch is assigned country[0] before the first iteration, country[1] before the second, and so on. The loop iterates twenty-four times (once per character), and the if body is executed three times (once per uppercase letter).

Назад: Processing Items in a List
Дальше: Looping Over a Range of Numbers