【问题标题】:How do i properly format strings in python for a password generator?如何在 python 中为密码生成器正确格式化字符串?
【发布时间】:2019-02-01 18:11:51
【问题描述】:

所以我想做的是打印出带有数字和特殊字符的单词列表。现在,我目前正坚持使用范围内生成的数字打印单词。

我已经试过了:

word = input("Enter a word\n>")
firstLetter = word[0]
firstLetter = firstLetter.upper()
length = len(word)
newWord = firstLetter + word[1:length]
print("%s \n".join([str(num).zfill(2) for num in range(0, 10)]) % newWord)

我试过的:

word = input("Enter a word\n>")
firstLetter = word[0]
firstLetter = firstLetter.upper()
length = len(word)
newWord = firstLetter + word[1:length]
print("\n".join([str(num).zfill(2) for num in range(0, 10)]) % newWord)

我期待这样的事情:

Password01
Password02
Password03
Password04
Password05
Password06
Password07
Password08

等等

我的结果:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
Enter a word
>pop
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print("\n".join([str(num).zfill(2) for num in range(0, 10)]) % newWord)
TypeError: not all arguments converted during string formatting

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    您可以将.title() 将字符串的第一个字母大写,然后使用range() 生成数字并使用f-strings 对其进行格式化:

    word = input("Enter a word\n>")
    word = word.title()
    for x in range(1, 9):
        print(f'{word}0{x}')
    

    注意:如果使用它的全部目的不是生成列表,则不要使用列表理解。

    【讨论】:

    • {x:02} 可能是对数字进行零填充的更好方法,如果它可能超过 10(在某些未来版本的代码中,range 更大)。前导 0 表示零填充,2 表示填充到两个字符的宽度。
    【解决方案2】:

    您可以使用大写来更改单词首字母的大小写。此外,您用于附加输入密码编号的代码是错误的。

    试试下面的代码:

    word = raw_input("Enter a word\n>")
    word = word.capitalize()
    for i in range(1, 10):
        print (word + '0' + str(i))
    

    输出:

    Enter a word
    >password
    Password01
    Password02
    Password03
    Password04
    Password05
    Password06
    Password07
    Password08
    Password09
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-22
      • 2012-07-22
      • 2014-10-12
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多