6

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?

Matt Swain
  • 3,827
  • 4
  • 25
  • 36

3 Answers3

11
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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • If your input isn't a string, you can put the desired characters right in the expression. I wanted file letters starting with 'a', so map(chr, range(ord('a'), ord('a') + 5)) – Dave Cameron Jul 04 '13 at 13:24
  • 10 years later... make nicer with lambda: `lis = lambda a,b: list(map(chr, range(ord(a), ord(b) + 1)))`, then `lis('a','z')` – ishahak Sep 10 '22 at 19:09
4

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']
Community
  • 1
  • 1
eldarerathis
  • 35,455
  • 10
  • 90
  • 93
1
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']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504