'I've got the following code to randomly create a string of letters, but it makes some of them capitalised

I need the random string to be in lowercase - I tried a.lower(), but couldn't get it to work.

def random_char(y):
    return ''.join(random.choice(string.letters) for x in range(y))

I'm a complete novice, so clear and simple answers please, thanks!



Solution 1:[1]

Change your function to

def random_char(y):
    return ''.join(random.choice(string.lowercase) for x in range(y))

(docs: https://docs.python.org/2/library/string.html#string.lowercase)

Solution 2:[2]

string.letters has too much stuff in it... but string.ascii_lowercase is right, so use it

>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> import random
>>> ''.join(random.choice(string.ascii_lowercase) for x in range(10))
'rathkzncdj'
>>> 

As an aside, random.sample does the loop for you

>>> ''.join(random.sample(string.ascii_lowercase, 10))
'hbegfsinqt'
>>> 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2314737
Solution 2