2015年5月21日 星期四

[ Python 常見問題 ] Random string generation with upper case letters and digits in Python

Source From Here 
Question 
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: 
* 6U1S75
* 4Z4UKK
* U911K4

How-To 
Answer in one line: 
  1. ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))  
A more secure version; see http://stackoverflow.com/a/23728630/2213647
  1. ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))  
In details, with a clean function for further reuse: 
  1. >>> import string  
  2. >>> import random  
  3. >>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):  
  4. ...    return ''.join(random.choice(chars) for _ in range(size))  
  5. ...  
  6. >>> id_generator()  
  7. 'G5G74W'  
  8. >>> id_generator(3"6793YUIO")  
  9. 'Y3U'  
How does it work ? 
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: 
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

Then we use a list comprehension to create a list of 'n' elements: 
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']

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: 
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'

Therefore random.choice(chars) for _ in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars: 
>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']

Then we just join them with an empty string so the sequence becomes a string: 
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'

Supplement 
[ Python 文章收集 ] Iterators & Generators

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...