Home > Enterprise >  I already got the answer but just curious why this method won't this work ? The output looks as
I already got the answer but just curious why this method won't this work ? The output looks as

Time:07-19

Write a program that takes a simple password and makes it stronger by replacing characters using the key below, and by appending "q*s" to the end of the input string.

  • i becomes !
  • a becomes @
  • m becomes M
  • B becomes 8
  • o becomes .
word = input()

password = ''

for x in word:

    if 'a' in x:
        password = word.replace('a', '@')
    if 'i' in x:
        password = word.replace('i', '!')
    if 'm' in x:
        password = word.replace('m', 'M')
    if 'B' in x:
        password = word.replace('B', '8')
    if 'o' in x:
        password = word.replace('o', '.')
        
print(password)

CodePudding user response:

You are assigning each replacement of word to password without updating word. So, it's stays the same.

Let's say the password is "ai":

First, it takes "a" and because "a" is in "a", it does

password = "@i"  # "ai".replace('a', '@')

Then, it takes "i" and because "i" is in "i", it does

password =  "a!" # "ai".replace('i', '!')

And you keep only the last assignement!

As commented by @chepner, you don't need to use an if statement, you can just call replace, and replacement are going to occur only if the character is present. Also, is not necessary to make a new assignment every time:

password = word.replace('a', '@')\
               .replace('i', '!')\
               .replace('m', 'M')\
               .replace('B', '8')\
               .replace('o', '.')

I like to write it like that, in multiple lines, so it's easy to keep track of the replacements.

Or maybe you want to state the replacements in a dictionary, so you can do:

replacements = {'a': '@', 'i': '!', 'm': 'M', 'B': '8', 'o': '.'}
password = word

for character in replacements.keys():
    password = password.replace(character, replacements[character])

CodePudding user response:

Just chain the replace statements together, e.g.:

'iBOoAF912Iib9'.replace('i','!').replace('a','@').replace('m','M').replace('B','8').replace('o','.')

CodePudding user response:

password = input()

password = password.replace('a', '@').replace('i', '!').replace('m', 'M').replace('B', '8').replace('o', '.')

print(password)
  • Related