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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-08 13:52

You have to convert the characters to numbers and back again.

for c in xrange(ord('a'), ord('z')+1):
    print chr(c) # resp. print unicode(c)

For the sake of beauty and readability, you can wrap this in a generator:

def character_range(a, b, inclusive=False):
    back = chr
    if isinstance(a,unicode) or isinstance(b,unicode):
        back = unicode
    for c in xrange(ord(a), ord(b) + int(bool(inclusive)))
        yield back(c)

for c in character_range('a', 'z', inclusive=True):
    print(chr(c))

This generator can be called with inclusive=False (default) to imitate Python's usual bhehaviour to exclude the end element, or with inclusive=True (default) to include it. So with the default inclusive=False, 'a', 'z' would just span the range from a to y, excluding z.

If any of a, b are unicode, it returns the result in unicode, otherwise it uses chr.

It currently (probably) only works in Py2.

查看更多
来,给爷笑一个
3楼-- · 2019-01-08 13:56
for character in map(   chr, xrange( ord('a'), ord('c')+1 )   ):
   print character

prints:

a
b
c
查看更多
看我几分像从前
4楼-- · 2019-01-08 13:56
# generating 'a to z' small_chars.
small_chars = [chr(item) for item in range(ord('a'), ord('z')+1)]
# generating 'A to Z' upper chars.
upper_chars = [chr(item).upper() for item in range(ord('a'), ord('z')+1)]
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-08 13:57

Using @ned-batchelder's answer here, I'm amending it a bit for python3

def char_range(c1, c2):
    """Generates the characters from `c1` to `c2`, inclusive."""
    """Using range instead of xrange as xrange is deprecated in Python3""" 
    for c in range(ord(c1), ord(c2)+1):
        yield chr(c)

Then same thing as in Ned's answer:

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

Thanks Ned!

查看更多
再贱就再见
6楼-- · 2019-01-08 14:02

This is a great use for a custom generator:

Python 2:

def char_range(c1, c2):
    """Generates the characters from `c1` to `c2`, inclusive."""
    for c in xrange(ord(c1), ord(c2)+1):
        yield chr(c)

then:

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

Python 3:

def char_range(c1, c2):
    """Generates the characters from `c1` to `c2`, inclusive."""
    for c in range(ord(c1), ord(c2)+1):
        yield chr(c)

then:

for c in char_range('a', 'z'):
    print(c)
查看更多
一夜七次
7楼-- · 2019-01-08 14:02

If you have a short fixed list of characters, just use Python's treatment of strings as lists.

for x in 'abcd':
    print x

or

[x for x in 'abcd']
查看更多
登录 后发表回答