I have a python question called the "Password modifier" where a user enters a password of their choice (ie mypassword
) and the program needs to change the following.
i becomes !
a becomes @
m becomes M
B becomes 8
o becomes .
Any suggestions?
You can use str.translate
and str.maketrans
>>> s = 'mypassword'
>>> s.translate(s.maketrans('iamBo', '!@M8.'))
'Myp@ssw.rd'
You can also harcode the shifting letters. Answers below are better but you can go like:
new_pass = ''
for char in password:
if char == 'i':
new_pass += '!'
elif char == 'a':
new_pass +='@'
elif char == 'm':
new_pass +='M'
.
.
.
else:
new_pass += char
I am familiar with this lab. The easiest approach is to use the replace() feature. Don't forget to use string concatenation for the "q*s" needed at the end of the modified password:
user_input = input()
string_append = "q*s"
user_input = (user_input.replace('i', '!').replace('a','@')
.replace('m', 'M').replace('B', '8').replace('o','.'))
print(user_input + string_append)
What about using the replace method for each character?
>>> password = 'mypassword'
>>> password = password.replace('a','@')
>>> print(password)
myp@ssword
Try the following:
chars={'i': '!', 'a': '@', 'm': 'M', 'B': '8', 'o':'.'}
password = input("Your password: ")
for x in password:
if x in chars:
password=password.replace(x, chars[x])
print(password)
1.Setup initial replacement....
text = "iamBo"
repl = "!@M8."
trans = str.maketrans(text,repl)
2.Get the password....
password = input()
3.Print the password....
print(password.translate(trans))
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.