Instead of making a list of alphabet characters like this:
alpha = ['a', 'b', 'c', 'd'.........'z']
is there any way that we can group it to a range or something? For example, for numbers it can be grouped using range()
:
range(1, 10)
To produce a range of letters (characters) in Python, you have to write a custom function that: Takes start and end characters as input. Converts start and end to numbers using ord() function. Generates a range of numbers between start and end.
The isalpha() function is a built-in function used for string handling in python, which checks if the single input character is an alphabet or if all the characters in the input string are alphabets.
The Python module string is readily available and contains pre-defined constant values that we can use for this problem. The constant string. ascii_lowercase contains all 26 lowercase characters in string format.
>>> import string >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz'
If you really need a list:
>>> list(string.ascii_lowercase) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
And to do it with range
>>> list(map(chr, range(97, 123))) #or list(map(chr, range(ord('a'), ord('z')+1))) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Other helpful string
module features:
>>> help(string) # on Python 3 .... DATA ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' hexdigits = '0123456789abcdefABCDEF' octdigits = '01234567' printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' whitespace = ' \t\n\r\x0b\x0c'
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