how to change a password with a modifer in python

Viewed 36

Many user-created passwords are simple and easy to guess. 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 .

Ex: If the input is: mypassword

the output is: Myp@ssw.rdq*s

Hint: Python strings are immutable, but support string concatenation. Store and build the stronger password in the given password variable.

Here is my code :

password = ''
char_counter = 0

while char_counter <= len(word):
    if word[char_counter] == ' i ':
      password = password =  ' ! '
    elif word[char_counter] == ' a ':
      password = password + ' @ '
    elif word[char_counter] == ' m ':
      password = password + ' M '
    elif word[char_counter] == ' B ':
      password = password + ' 8 '
    elif word[char_counter] == ' o ':
      password = password + ' . '
    
    else:
        password = password + word[char_counter]
        char_counter = char_counter + 1

I keep getting errors on this:

Traceback (most recent call last): File "main.py", line 6, in if word[char_counter] == ' i ': IndexError: string index out of range

3 Answers

Strings are indexed starting from 0 in Python, so checking that char_counter is less than or equal to the length of the string will create this error. Instead check that it is less than the length of the string.

The best way to accomplish this is likely with str.translate and (in Python 3.10) bytes.maketrans.

translation = bytes.maketrans(b'iamBo', b'!@M8.')
password = f"{word.translate(translation)}q*s"

First of all, indexes starts from 0 so you want to go to len-1, that is causing the error.

...
while char_counter < len(word):
...

Secondly, none of the conditions will ever be true, since your comparing one char to three chars.

And finally, maybe you want to increment the counter outside the else block, since you will go to infinite loop if any of the conditions will ever be true.

In python you do not need to iterate over the whole string. Just use .replace()

def improve_pw(s):
    # i becomes ! a becomes @ m becomes M B becomes 8 o becomes .
    return s.replace('i', '!') \
            .replace('a', '@') \
            .replace('m', 'M') \
            .replace('B', '8') \
            .replace('o', '.') + "q*s"


if __name__ == '__main__':
    print(improve_pw('mypassword'))

Related