range over character in python

2019-01-08 13:29发布

Is there an way to range over characters? something like this.

for c in xrange( 'a', 'z' ):
    print c

I hope you guys can help.

13条回答
▲ chillily
2楼-- · 2019-01-08 13:41
import string
for char in string.ascii_lowercase:
    print char

See string constants for the other possibilities, including uppercase, numbers, locale-dependent characters, all of which you can join together like string.ascii_uppercase + string.ascii_lowercase if you want all of the characters in multiple sets.

查看更多
Anthone
3楼-- · 2019-01-08 13:45

Use list comprehension:

for c in [chr(x) for x in range(ord('a'), ord('z'))]:
    print c
查看更多
走好不送
4楼-- · 2019-01-08 13:46

Another option (operates like range - add 1 to stop if you want stop to be inclusive)

>>> import string
>>> def crange(arg, *args):
...     """character range, crange(stop) or crange(start, stop[, step])"""
...     if len(args):
...         start = string.ascii_letters.index(arg)
...         stop = string.ascii_letters.index(args[0])
...     else:
...         start = string.ascii_letters.index('a')
...         stop = string.ascii_letters.index(arg)
...     step = 1 if len(args) < 2 else args[1]
...     for index in range(start, stop, step):
...         yield string.ascii_letters[index]
...
>>> [_ for _ in crange('d')]
['a', 'b', 'c']
>>>
>>> [_ for _ in crange('d', 'g')]
['d', 'e', 'f']
>>>
>>> [_ for _ in crange('d', 'v', 3)]
['d', 'g', 'j', 'm', 'p', 's']
>>>
>>> [_ for _ in crange('A', 'G')]
['A', 'B', 'C', 'D', 'E', 'F']
查看更多
爷的心禁止访问
5楼-- · 2019-01-08 13:51

There are other good answers here (personally I'd probably use string.lowercase), but for the sake of completeness, you could use map() and chr() on the lower case ascii values:

for c in map(chr, xrange(97, 123)):
   print c
查看更多
Explosion°爆炸
6楼-- · 2019-01-08 13:51

I like an approach which looks like this:

base64chars = list(chars('AZ', 'az', '09', '++', '//'))

It certainly can be implemented with a lot of more comfort, but it is quick and easy and very readable.

Python 3

Generator version:

def chars(*args):
    for a in args:
        for i in range(ord(a[0]), ord(a[1])+1):
            yield chr(i)

Or, if you like list comprehensions:

def chars(*args):
    return [chr(i) for a in args for i in range(ord(a[0]), ord(a[1])+1)]

The first yields:

print(chars('ĀĈ'))
<generator object chars at 0x7efcb4e72308>
print(list(chars('ĀĈ')))
['Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ']

while the second yields:

print(chars('ĀĈ'))
['Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ']

It is really convenient:

base64chars = list(chars('AZ', 'az', '09', '++', '//'))
for a in base64chars:
   print(repr(a),end='')
print('')
for a in base64chars:
   print(repr(a),end=' ')

outputs

'A''B''C''D''E''F''G''H''I''J''K''L''M''N''O''P''Q''R''S''T''U''V''W''X''Y''Z''a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''s''t''u''v''w''x''y''z''0''1''2''3''4''5''6''7''8''9''+''/'
'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' '+' '/' 

Why the list()? Without base64chars might become a generator (depending on the implementation you chose) and thus can only be used in the very first loop.

Python 2

Similar can be archived with Python 2. But it is far more complex if you want to support Unicode, too. To encourage you to stop using Python 2 in favor of Python 3 I do not bother to provide a Python 2 solution here ;)

Try to avoid Python 2 today for new projects. Also try to port old projects to Python 3 first before extending them - in the long run it will be worth the effort!

Proper handling of Unicode in Python 2 is extremely complex, and it is nearly impossible to add Unicode support to Python 2 projects if this support was not build in from the beginning.

Hints how to backport this to Python 2:

  • Use xrange instead of range
  • Create a 2nd function (unicodes?) for handling of Unicode:
    • Use unichr instead of chr to return unicode instead of str
    • Never forget to feed unicode strings as args to make ord and array subscript work properly
查看更多
别忘想泡老子
7楼-- · 2019-01-08 13:51

Inspired from the top post above, I came up with this :

map(chr,range(ord('a'),ord('z')+1))                     
查看更多
登录 后发表回答