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?
The easiest way to load a list of all the letters of the alphabet is to use the string. ascii_letters , string. ascii_lowercase , and string. ascii_uppercase instances.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With