String 如何在Python中多次替换和更新字符串?
我正在做一个测验项目,需要一些帮助。我试图一次替换一个单词,但是Python没有保存以前替换的字符串。下面是我的意思的一个小例子:String 如何在Python中多次替换和更新字符串?,string,python-2.7,replace,String,Python 2.7,Replace,我正在做一个测验项目,需要一些帮助。我试图一次替换一个单词,但是Python没有保存以前替换的字符串。下面是我的意思的一个小例子: replacedQuiz="" easyQuiz = """ You can change a string variable to an integer by typing (__1__) in front of the variable. It also works vice versa, you can change an integer variable
replacedQuiz=""
easyQuiz = """
You can change a string variable to an integer by typing (__1__)
in front of the variable. It also works vice versa, you can change an
integer
variable to a string by typing (__2__). This is important to remember before
you __3__ strings together, or else a TypeError will occur. While adding an
integer to a string, it is important to separate it using a __4__ (use the
symbol). \n"""
def replaceWord(replaced, quiz, numCount):
if numCount == 1:
replaced = quiz.replace("__1__", "int")
if numCount == 2:
replaced = replaced.replace("__2__", "str")
if numCount == 3:
replaced= replaced.replace("__3__", "concatenate")
if numCount == 4:
replaced= replaced.replace("__4__", ",")
print replaced
def easy():
QCount=1
print easyQuiz
while QCount < 5:
replaceWord(replacedQuiz, easyQuiz, QCount)
QCount += 1
print easy()
我认为,通过创建一个名为replacedquick的字符串,它将保存第一个替换,然后我可以继续替换测验中的单词并更新它。请帮忙!我不知道我错在哪里您似乎在变量替换测验的范围内犯了一个小错误。这当然建议您检查一下这个主题。基本上,您只是在当前函数中用它的新值替换replacedquick。其他函数只能访问前面定义的全局值。有几种方法可以解决此问题,例如全局关键字,但标准方法是从函数返回新的replacedquick 为此,请在replaceWord函数末尾添加以下行:
return replacedQuiz
这告诉Python在调用它的行中使用这个值。然后,只需将其定义为返回值,即可在easy中为ReplacedQuike定义一个新值:
replacedQuiz = replaceWord(replacedQuiz, easyQuiz, QCount)
在你的函数中,replacedquick不应该被替换吗?是的,很抱歉,我更新了它,使它成为我所拥有的更小的版本,但没有被替换。虽然我试过了,但还是不起作用。我编辑了它^^这很有效!!!非常感谢你,我已经被困在这几个小时了!没问题,只是很高兴它成功了。希望它教会了你一些东西;,我们都得从某个地方开始。如果你接受了这个答案,其他人就不会认为这个问题没有解决,他们可以帮助其他人:。