字符串没有加入Python

时间:2013-07-21 05:58:35

标签: python random terminal passwords generator

我正在尝试使用python创建一个简单的密码生成器,它会读取您使用以下格式提供的模式,A表示大写字符,a表示小写字符,$数字和#符号。该模式将通过命令行参数和sys.exit()方法返回的输出给出。

由于某些原因,我的脚本无法正常工作,对我而言看起来很好我似乎无法弄清楚它有什么问题。它在我的终端窗口输出一个空白行。

#!/usr/bin/env python
# IMPORTS
import os
import sys
import random

alc = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
auc = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
num = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
sym = ["!", "#", "%", "&", "?", "@", "(", ")", "[", "]", "<", ">", "*", "+", ",", ".", "~", ":", ";", "=", "-", "_", "\\", "/"]

pattern = list(sys.argv[1])
password = ""

# PROCESSING

for x in pattern:
    if x == "A":
        random.shuffle(auc)
        password.join(auc[0])
    elif x == "a":
        random.shuffle(alc)
        password.join(alc[0])
    elif x == "$":
        random.shuffle(num)
        password.join(num[0])
    elif x == "#":
        random.shuffle(sym)
        password.join(sym[0])
    else:
        password = "ERROR: Invalid Syntax."
        break

# END PROCESSING

sys.exit(password)

3 个答案:

答案 0 :(得分:1)

字符串是不可变的,因此当您致电join()时,它不会更改password。它返回输出。

password.join(thelist[0])

应该是:

password = password.join(thelist[0])

因此,当您打印password时,只会显示'',因为您从未更改过它。

此处甚至不需要

join。你可以做password += auc[0]。我已在下面展示了这一点。

您也可以清理代码中的一些内容。 string模块将为您提供帮助:

>>> import string
>>> print list(string.lowercase)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> print list(string.uppercase)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
>>> print list(string.punctuation)
['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
>>> print list(string.digits)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

而不是随机播放列表,您可以使用random.choice()

for x in pattern:
    if x == "A":
        password += random.choice(auc)
    elif ...

答案 1 :(得分:1)

您必须使用password = password.join(alc[0])password += alc[0]

A.join(b)不会更改A。它创建一个与A+b相同的新字符串并返回它,但A保持不变。

答案 2 :(得分:1)

这是您想要做的更简单的版本:

import os
import sys
import random
import string

vals = {'a': string.ascii_lowercase,
        'b': string.ascii_uppercase,
        '$': '0123456789',
        '#': '!#%&?@()[]<>*+,.~:;=-_\\/',
       }

pattern = sys.argv[1]

password = ''.join(random.choice(vals[c]) for c in pattern) # assumes that there are no invalid characters in the input

password = ''.join(random.choice(vals[c][0]) for c in pattern if c in vals) # takes only the valid characters in the input

random.shuffle是一项相对昂贵的操作,会对整个列表进行洗牌。另一方面,random.choice在可迭代中选择一个随机元素。

希望这有帮助