Issue
I'm new to python and coding in general. Here is a problem from my homework, as well as my current code. I know that I only have one of the parts, but I wanted to figure this one out before moving on to the rest. With my loop, I can find and identify the letter i, but I can't figure out how to change the i's to 1's.
Problem:
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 "!" to the end of the input string.
i becomes 1 a becomes @ m becomes M B becomes 8 s becomes $
Ex: If the input is:
mypassword
the output is:
Myp@$$word!
Hint: Python strings are immutable, but support string concatenation. Store and build the stronger password in the given password variable.
Code:
word = input()
password = ()
for letter in word:
if letter == 'i':
password = password+'1'
else: password = password+letter
print(password)
input: igigigig output: igigigig
Solution
First off, you're initializing your password to an incorrect variable choice. password = ()
sets password to a tuple. Attempting to add characters to a tuple variable will lead to an exception:
>>> password = ()
>>> password = password + '1'
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
Next, you have a mapping of characters provided in the question. You can start by creating a dictionary to represent this mapping.
mapping = {
'i': '1',
'a': '@',
'm': 'M',
'B': '8',
's': '$',
}
When looping against letters you can use the mapping to determine if a replacement should be made:
for letter in word:
if letter in mapping:
password = password + mapping.get(letter)
else:
password = password + letter
You also forgot to add the !
to the end.
Final result:
mapping = {
'i': '1',
'a': '@',
'm': 'M',
'B': '8',
's': '$',
}
word = "mypassword"
password = ""
for letter in word:
if letter in mapping:
password = password + mapping[letter]
else:
password = password + letter
password += "!"
print(password)
Simplifying this further:
for letter in word:
password += mapping.get(letter, letter)
password += "!"
Even further with a comprehension!:
password = ''.join(mapping.get(l, l) for l in word) + "!"
Answered By - flakes
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.