-2

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 = ''

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)
Ryan Pattillo
  • 331
  • 1
  • 8
  • I don't see why this was edited to have the `if` statements in a loop. That would only make sense if the conditions were of the form `x == 'a'`. I assume `x` has the same value as `word` in which case `'a' in x` is `True` if the string `x` contains the `'a'` character. – Ryan Pattillo Jul 19 '22 at 00:52
  • You don't need the loop or the `if` statements. You just need to chain calls to `replace. – chepner Jul 19 '22 at 00:53
  • Or `str.translate` - [https://docs.python.org/3/library/stdtypes.html#str.translate](https://docs.python.org/3/library/stdtypes.html#str.translate). – wwii Jul 19 '22 at 03:41

2 Answers2

1

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])
Ignatius Reilly
  • 1,594
  • 2
  • 6
  • 15
0

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

'iBOoAF912Iib9'.replace('i','!').replace('a','@').replace('m','M').replace('B','8').replace('o','.')
njp
  • 620
  • 1
  • 3
  • 16