本文介绍了如何用 Python 中的另一个字符替换字符串中的一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用!"替换字符串aeiou"中不是i"的每个字符
I want to replace every character that isn't "i" in the string "aeiou" with a "!"
我写道:
def changeWord(word):
for letter in word:
if letter != "i":
word.replace(letter,"!")
return word
这只是返回原件.我怎样才能返回!!i!!"?
This just returns the original. How can I return "!!i!!"?
推荐答案
Python 中的字符串是不可变的,因此您不能就地更改它们.查看 str.replace 的文档:
Strings in Python are immutable, so you cannot change them in place. Check out the documentation of str.replace:
返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换.如果给出可选参数计数,仅替换第一个计数出现.
为了让它发挥作用,请执行以下操作:
So to make it work, do this:
def changeWord(word):
for letter in word:
if letter != "i":
word = word.replace(letter,"!")
return word
这篇关于如何用 Python 中的另一个字符替换字符串中的一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!