Fillethacker Ranjid
Fillethacker Ranjid

Reputation: 91

The for loop with letters instead of numbers

i know the for loop:

    for i range(2, 6):
        print i

gives this output:

    2
    3
    4
    5

can i also do this somehow with letters? for example:

    # an example for what i'm looking for
    for i in range(c, h):
        print i


    c
    d
    f
    g

Upvotes: 5

Views: 14003

Answers (5)

user2032433
user2032433

Reputation:

There's no reason not to use:

>>> for char in "cdefg":
...     print(char)
c
d
e
f
g

Even if you weren't a programmer, you could figure out what the loop does, it's basically English. It's also much cleaner, it's shorter, and the best part is that it's 6 times faster than the chr(ord()) solution:

>>> import timeit
>>> timeit.timeit("for i in 'abcdefg': x = i")
0.27417739599968627
>>> timeit.timeit("for i in range(ord('a'), ord('g') + 1): x = chr(i)")
1.7386019650002709

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304137

I think it's nicer to add 1 to ord('g') than using ord('h')

for code in range(ord('c'), ord('g') + 1):
    print chr(code)

because what if you want to go to 'z', you need to know what follows 'z' . I bet you can type + 1 faster than you can look it up.

Upvotes: 9

user764357
user764357

Reputation:

This also works, this way its very explicit what you are working with:

import string
s = string.ascii_lowercase
for i in s[s.index('c'):s.index('h')]:
    print i

Upvotes: 5

Tobias Hermann
Tobias Hermann

Reputation: 10936

How about this?

for code in range(ord('c'), ord('h')):
    print chr(code)

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

for i in 'cdefg':

...

for i in (chr(x) for x in range(ord('c'), ord('h'))):

Upvotes: 8

Related Questions