我对 python 和一般编码很陌生。这是我的作业中的一个问题,以及我当前的代码。我知道我只有其中一个部分,但我想在继续其余部分之前先弄清楚这一部分。通过我的循环,我可以找到并识别字母 i,但我不知道如何将 i 更改为 1。
问题:
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.
代码:
word = input()
password = ()
for letter in word:
if letter == 'i':
password = password+'1'
else: password = password+letter
print(password)
输入:igigigig
输出:igigigig
最佳答案
首先,您将密码初始化为错误的变量选择。 password = ()
将密码设置为元组。尝试向元组变量添加字符将导致异常:
>>> password = ()
>>> password = password + '1'
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
接下来,您将获得问题中提供的字符映射。您可以首先创建一个字典来表示此映射。
mapping = {
'i': '1',
'a': '@',
'm': 'M',
'B': '8',
's': '$',
}
当循环字母时,您可以使用映射来确定是否应该进行替换:
for letter in word:
if letter in mapping:
password = password + mapping.get(letter)
else:
password = password + letter
您还忘记将 !
添加到末尾。
最终结果:
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)
进一步简化:
for letter in word:
password += mapping.get(letter, letter)
password += "!"
进一步理解!:
password = ''.join(mapping.get(l, l) for l in word) + "!"
关于Python:循环并编辑字符串字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72877045/