Python生成随机字符串
时间:2020-02-23 14:42:44 来源:igfitidea点击:
我们可以使用random模块在Python中生成随机字符串。
有时我们想为唯一标识符,会话ID或者建议密码生成随机字符串。
Python生成随机字符串
我们定义实用程序函数,以根据给定的字符序列和指定的大小生成随机字符串。
import random import string def random_string_generator(str_size, allowed_chars): return ''.join(random.choice(allowed_chars) for x in range(str_size)) chars = string.ascii_letters + string.punctuation size = 12 print(chars) print('Random String of length 12 =', random_string_generator(size, chars))
输出:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;?@[\]^_"{|}~ Random String of length 12 = 'MP'?EI$MO%w
我们正在使用random.choice()函数从提供的字符序列中选择一个随机字符。
然后,我们使用for循环运行给定次数。
然后,我们使用字符串join()函数将它们连接起来并返回随机生成的字符串。
如果我们想将随机字符串的大小保留为变量,例如8到12个字符,该怎么办?让我们稍微调整一下功能以随机选择随机字符串的大小。
import random from random import randint import string def random_string_generator_variable_size(min_size, max_size, allowed_chars): return ''.join(random.choice(allowed_chars) for x in range(randint(min_size, max_size))) chars = string.ascii_letters + string.punctuation print('Random String of random length (6-12) =', random_string_generator_variable_size(6, 12, chars))
输出:Random String of random length(6-12)= d; @o /?[yq =
除了使用randint()
函数外,该代码与早期函数几乎相同。
这样做是为了随机选择随机生成的字符串的大小。
随机UUID生成
如果您想要基于RFC-4122规范的唯一ID,则可以使用Python uuid模块。
import uuid print('Random UUID from uuid1() =', uuid.uuid1()) print('Random UUID from uuid4() =', uuid.uuid4())
输出:
Random UUID from uuid1() = dcc1044e-d76b-11e8-b54e-186590db0e15 Random UUID from uuid4() = a0e98c8d-a6fd-4125-bc1c-69ffe6456cb6