python中的字符范围

2022-01-24 00:00:00 python range character

问题描述

有没有办法跨越字符?像这样的.

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

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

希望大家帮忙


解决方案

这是自定义生成器的绝佳用途:

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)

然后:

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)

相关文章