def random_id(length):
number = '0123456789'
alpha = 'abcdefghijklmnopqrstuvwxyz'
id = ''
for i in range(0,length,2):
id += random.choice(number)
id += random.choice(alpha)
return id
You haven't really said much about what sort of random string you need. But in any case, you should look into the random module.
下面粘贴了一个非常简单的解决方案。
import random
def randstring(length=10):
valid_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
return ''.join((random.choice(valid_letters) for i in xrange(length)))
print randstring()
print randstring(20)
Return a string of n random bytes suitable for cryptographic use.
此函数从特定于操作系统的随机性中返回随机字节
返回的数据应该足够不可预测,以便
加密应用程序,虽然它的确切质量取决于操作系统
在类 UNIX 系统上,这将查询/dev/urandom,
and on Windows it will use CryptGenRandom. If a randomness source is
not found, NotImplementedError will be raised.
此函数生成由大写、小写字母、数字组成的随机字符串,通过长度分隔符 no _ of _ block 来指定字符串格式
Len _ sep = 4,no _ of _ block = 4将生成以下模式,
F4nQ-Vh5z-JKEC-WhuS
其中,长度分隔符将添加4个字符后的“-”
XXXX-
No of 块将以字符串形式生成以下字符模式
XXXX-XXXX-XXXX-XXXX
如果需要一个随机字符串,只需将 no _ of _ block 变量保持为等于1,并使用 len _ sep 指定随机字符串的长度。
Len _ sep = 10,no _ of _ block = 1,将生成以下模式,即 长度10的随机字符串,
F01xgCdoDU
import random as r
def generate_random_string(len_sep, no_of_blocks):
random_string = ''
random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(0,len_sep*no_of_blocks):
if i % len_sep == 0 and i != 0:
random_string += '-'
random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
return random_string
import random
def randomWord(length=5):
consonants = "bcdfghjklmnpqrstvwxyz"
vowels = "aeiou"
return "".join(random.choice((consonants, vowels)[i%2]) for i in range(length))
import random
import string
def get_random_string(size):
chars = string.ascii_lowercase+string.ascii_uppercase+string.digits
''.join(random.choice(chars) for _ in range(size))
print(get_random_string(20)
The secrets module is used for generating cryptographically strong
random numbers suitable for managing data such as passwords, account
authentication, security tokens, and related secrets.
In particularly, secrets should be used in preference to the default
设计了随机模块中的伪随机数发生器
用于建模和模拟,而不是安全或加密。
在测试 768bit安全令牌的生成过程中,我发现:
random.choices()-0.000246秒
secrets.choice()-0.003529秒
secrets模块运行速度较慢,但除了测试之外,您还应该将它用于加密目的:
import string, secrets
def random_string(size):
letters = string.ascii_lowercase+string.ascii_uppercase+string.digits
return ''.join(secrets.choice(letters) for i in range(size))
print(random_string(768))