A for loop with letters instead of numbers

I know the for loop:

for i range(2, 6): print i 

gives this result:

  2 3 4 5 

Can I write with letters anyway? eg:

  # an example for what i'm looking for for i in range(c, h): print i c d f g 
+4
source share
5 answers

It seems to me nicer to add 1 to ord('g') than to use ord('h')

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

because if you want to go to z, you need to know what follows z. I bet you can dial + 1 faster than you can see.

+8
source
 for i in 'cdefg': 

...

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

It also works, so it is very clear what you are working with:

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

There is no reason not to use:

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

Even if you are not a programmer, you can understand what the loop does, it is mostly English. It is also much cleaner, shorter, and the best thing is that it is 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 
+2
source

How about this?

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

Source: https://habr.com/ru/post/1486762/


All Articles