[英]Empty variable in for-loop
我有這個單線工作完全正常。
import random
from string import ascii_letters, digits
def pwd_generator(pwd):
password = "".join([random.choice(ascii_letters + digits) for i in range(pwd)])
print(password)
我現在想把它翻譯成一個“正常”的 for 循環。
def pwd_generator(pwd):
password = ''
for i in range(pwd):
password.join([random.choice(ascii_letters + digits)])
print(password)
但是,在這種情況下, password
為空。
為什么當我嘗試在“適當的”for 循環中寫入變量時變量為空?
字符串是不可變的,因此password.join
返回一個字符串但不將其保存為密碼。 相反,您應該將字符串保存在列表中並在最后加入它們:
password = []
for i in range(pwd):
password.append(random.choice(ascii_letters + digits)
return "".join(password)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.