Python:循环并编辑字符串字符

标签 python python-3.x loops if-statement

我对 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/

相关文章:

java - 如何在循环中调用 keyPressed() 方法?

python - 使用 pandas 从标准化 csv 中提取下采样时间序列

python - 如何拟合包含具有可变极限的积分的函数?

python - 在跳过第一行并使用第二行作为 pandas 中符号的原始刻度数据的标题时,无法读取 csv

python - fbs 和 PyQt5 中的应用程序名称显示为未知

c - C算术怎么会这么不精确呢?

python - 从两个列表中找到最佳组合

python - 什么是 func_dict?

python - 防止 sleep 模式python(python上的Wakelock)

Javascript - HTML 中的对象循环和组织数据