且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python中的随机字符串

更新时间:2023-11-07 10:35:10

从(例如)小写字符生成字符串:

导入随机,字符串定义随机字(长度):字母 = string.ascii_lowercase返回 '​​'.join(random.choice(letters) for i in range(length))

结果:

>>>随机词(10)'vxnxikmhdc'>>>随机词(10)'ytqhdohksy'

How do you create a random string in Python?

I needed it to be number then character repeat till you're done this is what I created

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

Generating strings from (for example) lowercase characters:

import random, string

def randomword(length):
   letters = string.ascii_lowercase
   return ''.join(random.choice(letters) for i in range(length))

Results:

>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'