随机字符串生成器python

时间:2014-06-19 21:57:34

标签: python-3.x random rpython

我在Python中创建了一个简单的程序来生成一个包含5个数字的随机字符串:

import random

numcount = 5
fstring = ""

for num in range(19): #strings are 19 characters long
    if random.randint(0, 1) == 1:
        x = random.randint(1, 26)
        x += 96
        fstring += (chr(x).upper())
    elif not numcount == 0:
        x = random.randint(0, 9)
        fstring += str(x)
        numcount -= 1

print(fstring)

不太难,对吗?除了一个令人难以置信的奇怪的事情:它返回的字符串是随机长度。我已多次运行代码,以下是我的一些结果:

>>> ================================ RESTART ================================
>>> 
VQZ99HA5DER0CES4
>>> ================================ RESTART ================================
>>> 
05PS0T86LOZS
>>> ================================ RESTART ================================
>>> 
E2QX8296XK
>>> ================================ RESTART ================================
>>> 
M5X9K457QDNBPX

我无法弄清楚发生了什么......有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:8)

你把硬币翻了19次;有50%的时间你选了一个字母,另外50%你选了一个数字,但只有5次。如果您更频繁地点击数字选项,则不会添加任何内容

所以你构建一个字符串最多 19个字符,但它可以更短。平均而言,它是9.5个字母,5个数字。

如果您仍有要选择的号码,则只选择号码:

import string
import random

numcount = 5
chars = []

for num in range(19): #strings are 19 characters long
    if numcount and random.random() < 0.5:
        chars.append(str(random.randint(0, 9)))
        numcount -= 1
    else:
        chars.append(random.choice(string.ascii_uppercase))

fchars = ''.join(chars)

演示:

>>> import string
>>> import random
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> numcount = 5
>>> chars = []
>>> for num in range(19): #strings are 19 characters long
...     if numcount and random.random() < 0.5:
...         chars.append(str(random.randint(0, 9)))
...         numcount -= 1
...     else:
...         chars.append(random.choice(string.ascii_uppercase))
... 
>>> ''.join(chars)
'3M6G97OEHP6TGYRONPV'
>>> len(chars)
19

答案 1 :(得分:0)

import random

numcount = 5
fstring = ""


while numcount > 0:
    if random.randint(0, 1) == 1:
        x = random.randint(1, 26)
        x += 96
        fstring += (chr(x).upper())
    elif not numcount == 0:
        x = random.randint(0, 9)
        fstring += str(x)
    numcount -= 1

print(fstring)