Sequence of letters in Python

John picture John · Oct 11, 2012 · Viewed 17.1k times · Source

Is there a built-in method / module in Python to generate letters such as the built-in constant LETTERS or letters constant in R?

The R built-in constant works as letters[n] where if n = 1:26 the lower-case letters of the alphabet are produced.

Thanks.

Answer

Jon Clements picture Jon Clements · Oct 11, 2012

It's called string.ascii_lowercase.

If you wanted to pick n many random lower case letters, then:

from string import ascii_lowercase
from random import choice

letters = [choice(ascii_lowercase) for _ in range(5)]

If you wanted it as a string, rather than a list then use str.join:

letters = ''.join([choice(ascii_lowercase) for _ in range(5)])