Range of Characters in Python

Suppose we want to generate a range of characters, similar to how the range() function returns a list of numbers between a given range.
This can be easily achieved with special constants in the string module.

To get the range between ‘a’ and ‘z’, we can use string.ascii_lowercase.

For example:

import string

for char in string.ascii_lowercase:
  print(char)

Output:

a
b
c
...
z

To generate the range between ‘A’ and ‘Z’, we can use string.ascii_uppercase.

For example:

import string

for char in string.ascii_uppercase:
  print(char)

Output:

A
B
C
...
Z

The constants can be used like any list, e.g. for iteration or testing membership of an element.

 

Leave a Reply

Your email address will not be published. Required fields are marked *