Expand alphabetical range to character list in Python

I have lines describing a range of characters in alphabetical order, consisting of two characters separated by a hyphen. I would like to expand them into a list of individual characters, such as:

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

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

+6
source share
3 answers
 In [19]: s = 'BF' 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() .

PS Since you need a list, the list(map(...)) construct can be replaced with a list comprehension.

+11
source

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

 >>> s = "AF" >>> [chr(item) for item in range(ord(s[0]), ord(s[-1])+1)] ['A', 'B', 'C', 'D', 'E', 'F'] 
+4
source
 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')) 

exit:

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

Source: https://habr.com/ru/post/916478/


All Articles