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
CodePudding user response:
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) "!"
CodePudding user response:
you can flow the step below
- 1.Change str(word) to list off str(letter)
- 2.Use loop check and change str(letter) in list one by one
- 3.Merge list off str(letter) to str(word)
Code :
word = list(word)
for position in range(len(word)):
letter = word[position]
if letter == 'i':
word[position] = '1'
''.join(word)
CodePudding user response:
with the help of some of these comments and re-reading the instructions, I was able to find the right answer that the book was looking for.
word = input()
password=''
for letter in word:
if letter == 'i':
str1 = '1'
password = password str1
else: password = password letter
print(password)