Matt Swain
Matt Swain

Reputation: 3887

Expand alphabetical range to list of characters in Python

I have strings describing a range of characters alphabetically, made up of two characters separated by a hyphen. I'd like to expand them out into a list of the individual characters like this:

'a-d' -> ['a','b','c','d']
'B-F' -> ['B','C','D','E','F']

What would be the best way to do this in Python?

Upvotes: 6

Views: 2449

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

import string

def lis(strs):
    upper=string.ascii_uppercase
    lower=string.ascii_lowercase

    if strs[0] in upper:        
        return list(upper[upper.index(strs[0]): upper.index(strs[-1])+1])
    if strs[0] in lower:
        return list(lower[lower.index(strs[0]): lower.index(strs[-1])+1])

print(lis('a-d'))
print(lis('B-F'))

output:

['a', 'b', 'c', 'd']
['B', 'C', 'D', 'E', 'F']

Upvotes: 1

eldarerathis
eldarerathis

Reputation: 36193

Along with aix's excellent answer using map(), you could do this with a list comprehension:

>>> s = "A-F"
>>> [chr(item) for item in range(ord(s[0]), ord(s[-1])+1)]
['A', 'B', 'C', 'D', 'E', 'F']

Upvotes: 4

NPE
NPE

Reputation: 500257

In [19]: s = 'B-F'

In [20]: list(map(chr, range(ord(s[0]), ord(s[-1]) + 1)))
Out[20]: ['B', 'C', 'D', 'E', 'F']

The trick is to convert both characters to their ASCII codes, and then use range().

P.S. Since you require a list, the list(map(...)) construct can be replaced with a list comprehension.

Upvotes: 11

Related Questions