我刚开始学习python,我想知道出了什么问题 这个for循环和/或if语句。
我试图循环查看单词列表,如果我找到的话 单词“right”我想用“left”替换它。
def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
mlist = list(phrases)
for word in mlist:
if word == "right":
word = "left"
output = ','.join(mlist)
return output
phrases = ("left", "right", "left", "stop")
left_join(phrases)
我应该得到这个
"left,left,left,stop"
但我得到
"left,right,left,stop"
所以“右”不会被“左”所取代。为什么呢?
答案 0 :(得分:2)
引用official documentation on for loop,
为expression_list的结果创建了一个迭代器。然后,对于迭代器提供的每个项,按升序索引的顺序执行一次该套件。
因此re
不会更改,此处仅更改>>> import re
>>> string = "/foo13546897/bar/Atlantis-GPS-coordinates/bar457822368/foo/"
>>> re.search(r'(?<=/bar/)[^/]+(?=/)', string).group()
'Atlantis-GPS-coordinates'
答案 1 :(得分:1)
请尝试以下代码:
def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
mlist = list(phrases)
for i in range(len(mlist)):
if mlist[i] == "right":
mlist[i] = "left"
output = ','.join(mlist)
return output
phrases = ("left", "right", "left", "stop")
output = left_join(phrases)
print(output)