Is it possible to make a letter range in python?

前端 未结 8 1544
误落风尘
误落风尘 2021-01-02 17:23

Is there a way to do a letter range in python like this:

for x in range(a,h,)
相关标签:
8条回答
  • 2021-01-02 17:45

    You can use ord() to convert the letters into character ordinals and back:

    def char_range(start, end, step=1):
        for char in range(ord(start), ord(end), step):
            yield chr(char)
    

    It seems to work just fine:

    >>> ''.join(char_range('a', 'z'))
        'abcdefghijklmnopqrstuvwxy'
    
    0 讨论(0)
  • 2021-01-02 17:49

    how about slicing an already pre-arranged list?

    import string
    
    s = string.ascii_lowercase
    print( s[ s.index('b'):s.index('o')+1 ] )
    
    0 讨论(0)
  • 2021-01-02 17:55

    Emanuele's solution is great as long as one is only asking for a range of single characters, which I will admit is what the original questioner posed. There are also solutions out there to generate all multi-character combinations: How to generate a range of strings from aa... to zz. However I suspect that someone who wants a character like range function might want to be able to deal with generating an arbitrary range from say 'y' to 'af' (rolling over from 'z' to 'aa'). So here is a more general solution that includes the ability to either specify the last member of the range or its length.

    def strange(start, end_or_len, sequence='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
        """Create a generator of a range of 'sequential' strings from
        start to end_or_len if end_or_len is a string or containing
        end_or_len entries if end_or_len is an integer.
    
        >>> list(strange('D', 'F'))
        ['D', 'E', 'F']
        >>> list(strange('Y', 'AB'))
        ['Y', 'Z', 'AA', 'AB']
        >>> list(strange('Y', 4))
        ['Y', 'Z', 'AA', 'AB']
        >>> list(strange('A', 'BAA', sequence='AB'))
        ['A', 'B', 'AA', 'AB', 'BA', 'BB', 'AAA', 'AAB', 'ABA', 'ABB', 'BAA']
        >>> list(strange('A', 11, sequence='AB'))
        ['A', 'B', 'AA', 'AB', 'BA', 'BB', 'AAA', 'AAB', 'ABA', 'ABB', 'BAA']
        """
        seq_len = len(sequence)
        start_int_list = [sequence.find(c) for c in start]
        if isinstance(end_or_len, int):
            inclusive = True
            end_int_list = list(start_int_list)
            i = len(end_int_list) - 1
            end_int_list[i] += end_or_len - 1
            while end_int_list[i] >= seq_len:
                j = end_int_list[i] // seq_len
                end_int_list[i] = end_int_list[i] % seq_len
                if i == 0:
                    end_int_list.insert(0, j-1)
                else:
                    i -= 1
                    end_int_list[i] += j
        else:
            end_int_list = [sequence.find(c) for c in end_or_len]
        while len(start_int_list) < len(end_int_list) or start_int_list <= end_int_list:
            yield ''.join([sequence[i] for i in start_int_list])
            i = len(start_int_list)-1
            start_int_list[i] += 1
            while start_int_list[i] >= seq_len:
                start_int_list[i] = 0
                if i == 0:
                    start_int_list.insert(0,0)
                else:
                    i -= 1
                    start_int_list[i] += 1
    
    
    if __name__ =='__main__':
        import doctest
        doctest.testmod()
    
    0 讨论(0)
  • 2021-01-02 17:56

    There is no built in letter range, but you can write one:

    def letter_range(start, stop):
        for c in xrange(ord(start), ord(stop)):
            yield chr(c)
    
    
    for x in letter_range('a', 'h'):
        print x,
    

    prints:

    a b c d e f g
    
    0 讨论(0)
  • 2021-01-02 18:02
    import string
    
    def letter_range(f,l,al = string.ascii_lowercase):
        for x in al[al.index(f):al.index(l)]:
            yield x
    
    print ' '.join(letter_range('a','h'))
    

    result

    a b c d e f g
    
    0 讨论(0)
  • 2021-01-02 18:03

    Something like:

    [chr(i) for i in range(ord('a'),ord('h'))]
    

    Will give a list of alphabetical characters to iterate through, which you can then use in a loop

    for x in [chr(i) for i in range(ord('a'),ord('h'))]:
        print(x)
    

    or this will do the same:

    for x in map(chr, range(*map(ord,['a', 'h']))):
        print(x)
    
    0 讨论(0)
提交回复
热议问题