随机生成字符串赋值给变量

2024-07-03 05:40:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个密码生成器,其中包括3个部分。我能够生成随机字符串(例如tYVb),但是当我尝试将其存储为变量'mod'并尝试打印它时,该值的末尾附加了'None'(tYVbNone)。如何只将字符串存储到变量中以便进一步操作它?你知道吗

from random import *

number = 4;

def myFunc(length):
    while length > 0:
        rndNumber = randint(0, 51)

    print('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'[rndNumber], end='')
        length -= 1

mod = str(myFunc(number))
print (mod)

Tags: 字符串fromimportnonemod密码numberrandom
3条回答

我认为编写您正在寻找的代码的最干净的方法是这样做:

import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

def myFunc(length):
    return ''.join([random.choice(letters) for x in range(0,length)])

然后可以这样调用函数:

x = myFunc(10)
print(x)

产生如下输出:zWAGjUyhEZ

我将这样做(根据您目前提供的内容):

from random import *

number = 4;

def myFunc(length):
    value = ''
    while length > 0:
        rndNumber = randint(0, 51)
        value += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'[rndNumber]
        length -= 1
    return value

mod = myFunc(number)
print (mod)

目前的代码中有几个错误或遗漏。我在下面的代码中提供了一些注释,以突出代码的潜在改进或一些补充。你知道吗

from random import *

# you don't need a semi-colon after the 4
number = 4

def myFunc(length):

    # Since we are building a password, we want to start with an empty 
    #     password before the while loop.
    password = ''
    while length > 0:
        rndNumber = randint(0, 51)

        # This step builds a new password incrementally. As you go
        #     through the while loop, it adds a new character to the
        #     end of the password variable.
        password += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'[rndNumber]

        length -= 1
    return password

# you don't need to convert the output to a string using the code above
#     since the process builds a string.    
mod = myFunc(number)
print(mod)

正如查尔斯·达菲所说,随机选择()是一个更好的解决方案,使代码更具python风格:

random.choice()

此函数从一系列项目中随机选取(在引擎盖下,字符串被视为序列)。你知道吗

可以在上面的代码中插入这个片段来帮助清理它。你知道吗

letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
letter = random.choice(letters)
password += letter

相关问题 更多 >