python中字符的范围

2024-04-25 12:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以跨越字符范围?像这样的

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

我希望你们能帮忙


Tags: 方法infor字符printxrange
3条回答
import string
for char in string.ascii_lowercase:
    print char

请参阅string constants了解其他可能的字符,包括大写、数字、依赖于区域设置的字符,如果希望所有字符都在多个集中,则所有这些字符都可以像string.ascii_uppercase + string.ascii_lowercase一样连接在一起

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

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

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

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))

可以使用inclusive=False(默认值)调用此生成器,以模仿Python通常的bhehaviour来排除结束元素,或者使用inclusive=True(默认值)来包含它。因此,使用默认的inclusive=False'a', 'z'将仅跨越从ay的范围,不包括z

如果ab中的任何一个是unicode,则返回unicode格式的结果,否则使用chr

它目前(可能)只在Py2中工作

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

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)

然后:

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)

然后:

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

相关问题 更多 >