Question
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as:
How-To
Answer in one line:
- ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
- ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
- >>> import string
- >>> import random
- >>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
- ... return ''.join(random.choice(chars) for _ in range(size))
- ...
- >>> id_generator()
- 'G5G74W'
- >>> id_generator(3, "6793YUIO")
- 'Y3U'
We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.
string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:
Then we use a list comprehension to create a list of 'n' elements:
Instead of asking to create 'n' times the string elem, we will ask Python to create 'n' times a random character, picked from a sequence of characters:
Therefore random.choice(chars) for _ in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars:
Then we just join them with an empty string so the sequence becomes a string:
Supplement
* [ Python 文章收集 ] Iterators & Generators
沒有留言:
張貼留言