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:
  block

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.

For example, we 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 statement block is executed three times (once per uppercase letter).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset