Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 717
Matt Swain Avatar asked May 23 '12 16:05

Matt Swain


People also ask

How do I get a list of all letters 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.


1 Answers

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.

like image 125
NPE Avatar answered Sep 17 '22 14:09

NPE