Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The for loop with letters instead of numbers

Tags:

python

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
like image 540
Fillethacker Ranjid Avatar asked Jun 18 '13 07:06

Fillethacker Ranjid


2 Answers

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.

like image 143
John La Rooy Avatar answered Nov 08 '22 16:11

John La Rooy


for i in 'cdefg':

...

for i in (chr(x) for x in range(ord('c'), ord('h'))):
like image 41
Ignacio Vazquez-Abrams Avatar answered Nov 08 '22 15:11

Ignacio Vazquez-Abrams