I'm using the following simple code to generate a random string of length 10
from string import ascii_letters, digits
''.join(choice(ascii_letters + digits) for i in range(10))
The problem is that sometimes the first character of the string is a digit. I don't want that. I want the first character to be always a letter, and what comes after I don't care about.
I can solve this problem to joining two strings (one of length 1 and the other of length 9), and generating the first one based on the ascii_letters alone. However, I was wondering if there's a simpler approach.
You can also use random.choices()
:
result = random.choice(ascii_letters) + ''.join(random.choices(ascii_letters + digits, k=9))
to select k
elements. No need for range
or for
.