【问题标题】:How to change the output of this Python program如何更改此 Python 程序的输出
【发布时间】:2015-01-12 23:47:35
【问题描述】:

我写了一个简单的python密码生成器:

import string
import random

print "Password generator will create a random customizable password."
print "Choose your options wisely."

number = int(raw_input("How many letters do you want in your password?"))
caps = str(raw_input("Do you want capital letters in your password? Y/N:"))
symbols = str(raw_input( "Do you want punctuation and other symbols in your password?    Y/N:"))
otherchoice = str(raw_input( "Do you want numbers in your password? Y/N:"))

punctuation = ("!", ".", ":", ";", ",", "?", "'", "@", "$", "~", "^","%", "#", "&", "/")
numbers = map(str,range(0,10))
stringpunctuation = "".join(punctuation)
stringnumbers = "".join(numbers)
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase

if caps == "Y":
    characters = lowercase + uppercase
else:
    characters = lowercase

if symbols == "Y":
    characters += stringpunctuation
if otherchoice == "Y":
    characters += stringnumbers

password = random.sample(characters, number)
print "The password is", password

这是我运行终端时出现的示例:

Password generator will create a random customizable password.
Choose your options wisely.
How many letters do you want in your password?15
Do you want capital letters in your password? Y/N:Y
Do you want punctuation and other symbols in your password? Y/N:Y
Do you want numbers in your password? Y/N:Y
The password is ['x', 'p', 'E', 'X', 'V', '#', ',', '@', 'q', 'N', 'F', 'U', 'b', 'W', '.']

我怎样才能使输出是这样的(在示例中使用密码): xpEXV#,@qNFUbW.

我真的不需要知道答案,实际结果会一样,我只是超级好奇。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    将字符与str.join() method一起加入;选择一个连接字符串并在其上调用方法,传入您的列表:

    password = ''.join(password)
    

    这将字符与空字符串 ('') 连接起来:

    >>> password = ['x', 'p', 'E', 'X', 'V', '#', ',', '@', 'q', 'N', 'F', 'U', 'b', 'W', '.']
    >>> ''.join(password)
    'xpEXV#,@qNFUbW.'
    

    对于其他用途,您可以选择不同的连接器:

    >>> '->'.join(password)
    'x->p->E->X->V->#->,->@->q->N->F->U->b->W->.'
    >>> '...'.join(password)
    'x...p...E...X...V...#...,...@...q...N...F...U...b...W....'
    

    【讨论】:

    • 非常感谢,我现在觉得自己好蠢,特别是因为我已经知道如何使用 "".join。我会尽快接受你的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多