Loop through each character of a string with a for loop

The Apollo Theater

apollo.py

During each iteration of the loop in lines 16–17, the variable c contains a string of one character. For example, during the first iteration of the loop, c contains "A". During the second iteration of the loop, c contains "P".

We can loop through the string s in line 16 because a string is iterable.

A
P
O
L
L
O

A
P
O
L
L
O

Print the index numbers too.

The above for loop prints only the characters, not the index numbers. If you need the indices too,

s = "APOLLO"

for i in range(len(s)):
    print(i, s[i])

print()

for i, c in enumerate(s):
    print(i, c)
0 A
1 P
2 O
3 L
4 L
5 O

0 A
1 P
2 O
3 L
4 L
5 O

Start the indices at 1.

s = "APOLLO"

for i, c in enumerate(s):
    print(i + 1, c)

print()

for i, c in enumerate(s, start = 1):
    print(i, c)
1 A
2 P
3 O
4 L
5 L
6 O

1 A
2 P
3 O
4 L
5 L
6 O

Another example of looping through the characters of a string

"""
Print the code number and catagory of each printable ASCII character.
"""

import sys

#A string of 95 characters.
#Within a double-quoted string, need backslash in front of " and \

s = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"

#Another way to create the same s:
#start = ord(" ")
#stop = ord("~") + 1
#listOfCharacters = [chr(code) for code in range(start, stop)]
#s = "".join(listOfCharacters)

#Also include the exotic whitespace characters 9 ("\t"), 10 ("\n"), 11 ("\v"), 12 ("\f").
#s = sorted(string.printable)   #import string

for c in s:
    if c.isupper():
        category = "upper"
    elif c.islower():
        category = "lower"
    elif c.isdigit():
        category = "digit"
    elif c.isspace():
        category = "space"
    else:
        category = "miscellaneous"

    print(f"{ord(c):3} {c} {category}")   #ord stands for "ordinal".

sys.exit(0)
 32   space
 33 ! miscellaneous
 34 " miscellaneous
 35 # miscellaneous
 36 $ miscellaneous
 37 % miscellaneous
 38 & miscellaneous
 39 ' miscellaneous
 40 ( miscellaneous
 41 ) miscellaneous
 42 * miscellaneous
 43 + miscellaneous
 44 , miscellaneous
 45 - miscellaneous
 46 . miscellaneous
 47 / miscellaneous
 48 0 digit
 49 1 digit
 50 2 digit
 51 3 digit
 52 4 digit
 53 5 digit
 54 6 digit
 55 7 digit
 56 8 digit
 57 9 digit
 58 : miscellaneous
 59 ; miscellaneous
 60 < miscellaneous
 61 = miscellaneous
 62 > miscellaneous
 63 ? miscellaneous
 64 @ miscellaneous
 65 A upper
 66 B upper
 67 C upper
 68 D upper
 69 E upper
 70 F upper
 71 G upper
 72 H upper
 73 I upper
 74 J upper
 75 K upper
 76 L upper
 77 M upper
 78 N upper
 79 O upper
 80 P upper
 81 Q upper
 82 R upper
 83 S upper
 84 T upper
 85 U upper
 86 V upper
 87 W upper
 88 X upper
 89 Y upper
 90 Z upper
 91 [ miscellaneous
 92 \ miscellaneous
 93 ] miscellaneous
 94 ^ miscellaneous
 95 _ miscellaneous
 96 ` miscellaneous
 97 a lower
 98 b lower
 99 c lower
100 d lower
101 e lower
102 f lower
103 g lower
104 h lower
105 i lower
106 j lower
107 k lower
108 l lower
109 m lower
110 n lower
111 o lower
112 p lower
113 q lower
114 r lower
115 s lower
116 t lower
117 u lower
118 v lower
119 w lower
120 x lower
121 y lower
122 z lower
123 { miscellaneous
124 | miscellaneous
125 } miscellaneous
126 ~ miscellaneous

Don’t write a line longer than 80 characters. Backslashes can join lines explicitly.

#A string of 95 characters.
#Within a double-quoted string, need backslash in front of " and \

s = \
      " !\"#$%&'()*+,-./0123456789:;<=>?@" \
    + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
    + "[\\]^_`" \
    + "abcdefghijklmnopqrstuvwxyz" \
    + "{|}~"

A pair of parentheses can join lines implicitly:

#A string of 95 characters.
#Within a double-quoted string, need backslash in front of " and \

s = (
      " !\"#$%&'()*+,-./0123456789:;<=>?@"
    + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    + "[\\]^_`"
    + "abcdefghijklmnopqrstuvwxyz"
    + "{|}~"
)

Make a list of four categories. The attributes of an object (in this case, the object c) include the methods of the object.

categories = [
    ["isupper", "upper"],
    ["islower", "lower"],
    ["isdigit", "digit"],
    ["isspace", "space"]
]

for c in s:
    for category in categories:
        f = getattr(c, category[0]) #f is a method belonging to c, e.g., c.isupper or c.islower
        if f():                     #f() is True or False
            name = category[1]
            break
    else:
        name = "miscellaneous"

    print(f"{ord(c):3} {c} {name}")

Another example of looping through the characters of a string

See the Wikipedia article.

"""
Output the lyrics to "Swingin' the Alphabet".
"""

import sys
consonants = "BCDFGHJKLM"

#A string of 7 lines, each ending with a newline character.
#The string contains 18 pockets.

verse = """\
{} a {}a
{} e {}e
{} i {}ikky {}i
{} o {}o
{}ikky {}i {}o
{} u {}u
{}ikky {}i {}o {}u.
"""

for c in consonants:
    print(verse.format(c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c))

sys.exit(0)

Things to try

  1. Change the print statement from
        print(verse.format(c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c))
    
    to the following. For the second asterisk, see Unpacking Argument Lists.
        #args is a list of 18 strings.
        args = 18 * [c]   #Means the same thing as args = [c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c]
        print(verse.format(*args))