【问题标题】:How to replace given index in String with Dictionary value in python?如何用python中的字典值替换字符串中的给定索引?
【发布时间】:2021-10-01 23:30:09
【问题描述】:

指令是将字符串中的某些字符替换为字典中的相应值。

这是我的代码:

word = input()
password = ''
wordDict = {
    
    'i': '!',
    'a': '@',
    'm': 'M',
    'B': '8',
    'o': '.',
    
}

for i in range(len(word)):
    if word[i] in wordDict.keys():
        word.replace(word[i], wordDict.get(word[i]))
        i += 1
    else:
        i += 1

print(word)

我的代码的问题是给定的密码没有任何变化,也没有遍历 for 循环。

【问题讨论】:

  • 一些提示... 像for c in word 这样迭代字符串的字符更简洁。无需对索引变量i 大惊小怪。使用dict.get 在您的字典中查找c,但使用默认参数。 wordDict.get(c, c) 以便任何不在字典中的字符都映射到自身。最后,构建一个新字符串可能比就地修改word 更好。为此,您在字符串类上有 "".join() 方法。祝你好运!
  • 非常感谢您的提示,这很有帮助!

标签: python list dictionary for-loop indexing


【解决方案1】:

你的问题在于这一行:

word.replace(word[i], wordDict.get(word[i]))

Python 以及许多其他语言中的字符串是不可变的,这意味着您无法编辑字符串。

您正在调用的函数 (str.replace) 不会替换字符串中的字符,它会返回一个新的 str 替换字符。

如果你想让它有效地工作,最简单但幼稚的方法是用这一行替换它:

word = word.replace(word[i], wordDict.get(word[i]))

【讨论】:

  • 解决了!非常感谢,我也很感谢详尽的解释。
  • @svnrod 不用担心,祝你好运 python :)。请记住,您可以在满意后接受答案,以便将问题标记为已回答。
  • 是的,我接受了。感谢好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 2012-08-31
  • 2013-05-07
相关资源
最近更新 更多