python中的字符范围

hua*_*uan 67 python character range

有没有办法超越字符?这样的事情.

for c in xrange( 'a', 'z' ):
    print c
Run Code Online (Sandbox Code Playgroud)

我希望你们能帮忙.

Ned*_*der 87

这对于自定义生成器非常有用:

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)
Run Code Online (Sandbox Code Playgroud)

然后:

for c in char_range('a', 'z'):
    print c
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

然后:

for c in char_range('a', 'z'):
    print(c)
Run Code Online (Sandbox Code Playgroud)

  • 美丽!对于任何要复制它的人,请记住范围(1,3)迭代值1和2(而不是3),但char_range('a','c')将迭代'a','b'和'C'! (4认同)
  • 这样做的问题是,要生成 az,您需要知道 z 之后是哪个字符。不是特别舒服。可能最好避免使用名称“范围”(使用闭合范围或包容范围代替?) (2认同)

agf*_*agf 76

import string
for char in string.ascii_lowercase:
    print char
Run Code Online (Sandbox Code Playgroud)

有关其他可能性的信息,请参阅字符串常量,包括大写,数字,与语言环境相关的字符,所有这些都可以连接在一起,就像string.ascii_uppercase + string.ascii_lowercase您想要多个集合中的所有字符一样.


glg*_*lgl 24

您必须将字符转换为数字然后再转换回来.

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

为了美观和可读性,您可以将其包装在生成器中:

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))
Run Code Online (Sandbox Code Playgroud)

可以使用inclusive=False(默认)调用此生成器来模拟Python通常的bhehaviour以排除end元素,或者使用inclusive=True(默认)来包含它.因此,与默认的inclusive=False,'a', 'z'也只是涵盖从范围ay,排除z.

如果是unicode中的任何一个a,b则以unicode返回结果,否则使用chr.

它目前(可能)仅适用于Py2.

  • 你可以在生成器中隐藏它:看看我的答案. (3认同)
  • 你的意思是你更喜欢你脸上的ord和chr?如果你不得不多次这样做,你会在每个地方复制它?奇.. (2认同)

Gre*_*att 11

这里有其他好的答案(我个人可能会使用string.lowercase),但为了完整起见,你可以在小写的ascii值上使用map()chr():

for c in map(chr, xrange(97, 123)):
   print c
Run Code Online (Sandbox Code Playgroud)


Dan*_*nid 7

如果你有一个简短的固定字符列表,只需使用Python对字符串的处理作为列表.

for x in 'abcd':
    print x
Run Code Online (Sandbox Code Playgroud)

要么

[x for x in 'abcd']
Run Code Online (Sandbox Code Playgroud)


Tin*_*ino 6

我喜欢这样的方法:

base64chars = list(chars('AZ', 'az', '09', '++', '//'))
Run Code Online (Sandbox Code Playgroud)

当然可以更加舒适地实现它,但是它快速,容易并且可读性强。

Python 3

发电机版本:

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

或者,如果您喜欢列表推导:

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

第一个产量:

print(chars('??'))
<generator object chars at 0x7efcb4e72308>
print(list(chars('??')))
['?', '?', '?', '?', '?', '?', '?', '?', '?']
Run Code Online (Sandbox Code Playgroud)

而第二个产量:

print(chars('??'))
['?', '?', '?', '?', '?', '?', '?', '?', '?']
Run Code Online (Sandbox Code Playgroud)

真的很方便:

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

输出

'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' '+' '/' 
Run Code Online (Sandbox Code Playgroud)

为什么list()呢?没有base64chars可能成为生成器(取决于您选择的实现),因此只能在第一个循环中使用。

Python 2

类似的内容可以用Python 2存档。但是,如果您也想支持Unicode,则要复杂得多。为了鼓励您停止使用Python 2而转而使用Python 3,我在这里不想打扰提供Python 2解决方案;)

立即尝试避免将Python 2用于新项目。另外,在扩展旧项目之前,请先尝试将其移植到Python 3中-从长远来看,这是值得的!

在Python 2中正确处理Unicode极为复杂,如果从一开始就没有内置Unicode支持,则几乎不可能将其添加到Python 2项目中。

提示如何将其反向移植到Python 2:

  • 使用xrange代替range
  • 创建unicodes用于处理Unicode 的第二个函数(?):
    • 使用unichr而不是chr返回unicode代替str
    • 永远不要忘记输入unicode字符串args以使ord数组和下标正常工作


sec*_*rve 5

for character in map(   chr, xrange( ord('a'), ord('c')+1 )   ):
   print character
Run Code Online (Sandbox Code Playgroud)

打印:

a
b
c
Run Code Online (Sandbox Code Playgroud)


小智 5

# 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)]
Run Code Online (Sandbox Code Playgroud)


小智 5

对于大写字母:

for i in range(ord('A'), ord('Z')+1):
    print(chr(i))
Run Code Online (Sandbox Code Playgroud)

对于小写字母:

for i in range(ord('a'), ord('z')+1):
    print(chr(i))
Run Code Online (Sandbox Code Playgroud)