简体   繁体   中英

How do i properly format strings in python for a password generator?

So I'm trying to do is print out a list of words with numbers and special characters. Right now I'm currently stuck on printing the words with the words printing with the generated numbers in the range.

I've already tried:

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)

The I tried:

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)

I'm expecting something like:

Password01
Password02
Password03
Password04
Password05
Password06
Password07
Password08

etc.

My results:

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

You can do .title() to uppercase just first letter of a string and use range() to generate numbers and format them using f-strings:

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

Note : Don't use a list-comprehension if the whole purpose of using it is not to generate a list.

You can use capitalize to change the case of the first letter of a word. Also, your code for appending the number of the entered password is wrong.

Try the below code:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM