美文网首页
Python 中随机生成字母和数字等字符组成的string

Python 中随机生成字母和数字等字符组成的string

作者: Golden_humble | 来源:发表于2018-06-23 00:01 被阅读0次

先贴一个链接,主要参考以下链接 : Python生成字母和数字组成的随机字符串?
这里需要用到两个模块: random 和 string
random.choice(chars) 模块可以在chars中随机选择字符
string模块中自带的函数string.ascii_uppercase() string.ascii_lowercase()string.digits()分别可以生成 大小写英文字母和数字,code as follows:

import string

string.ascii_lowercase + string.digits
'abcdefghijklmnopqrstuvwxyz0123456789'

string.ascii_lowercase + " "
'abcdefghijklmnopqrstuvwxyz '

function is as follows:

import string
import random

def random_sentence(size):
    char_lists = string.ascii_lowercase + string.digits
    return ''.join(random.choice(char_lists) for _ in range(size))

结果如下:

random_sentence(28)
Out[141]: 'tn  nxs zzrzdoaeomdadzxobkki'

相关文章

网友评论

      本文标题:Python 中随机生成字母和数字等字符组成的string

      本文链接:https://www.haomeiwen.com/subject/qasweftx.html