LaurentiuS
LaurentiuS

Reputation: 314

Enumerating Ascii characters using range and enumerate

I'm new to this enumerate command and I'm not sure if I'm supposed to use it like this, what I want to do is to enumerate the ASCII characters from 0 - 129, and what I get is '1' before each character.

for x in range(129):
    xxx = chr(x)
    z = list(xxx)
    for i, a in enumerate(z, 1):
        print(i, a)

random text output:

1 .
1 /
1 0
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9

Upvotes: 1

Views: 288

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121544

You are looping over a list with a single character in it:

>>> xxx = chr(65)
>>> xxx
'A'
>>> list(xxx)
['A']
>>> len(list(xxx))
1

You then loop over the enumerate() result for that single character, so yes, you only get 1.

You repeat that inner loop for each value of x, so you do get it 129 times. It is your outer for x in range(129) loop that makes the 1s repeat.

You'd use enumerate() for the outer loop, and there's no point in turning your single character into a list each time:

for i, x in enumerate(range(129)):
    xxx = chr(x)
    print(i, xxx)

Note that x is already an increasing integer number however. enumerate() is really just overkill here. Just print x + 1 for the same number:

for x in range(129):
    xxx = chr(x)
    print(x + 1, xxx)

Upvotes: 2

Related Questions