【发布时间】:2016-10-21 23:54:36
【问题描述】:
如何替换列表中 index[3] 之后的每个单词?
例如,我需要将第一个单词更改为“How's”,将第二个单词更改为“it”,将第三个单词更改为“going?”。然后,我需要将 index[3] 之后的每个单词都更改为“yo”:
input = "My name is bla bla bla?"
output = "How's it going? Yo! Yo! Yo!"
这是我目前所拥有的:
def hellohello(input):
if type(input) != str:
return "Input has to be string"
else:
new_input = input.split(' ')
if len(input) <= 3:
return "How's it going?"
else:
new_input[0] = "How's "
new_input[1] = "it "
new_input[2] = "going? "
new_input[3:] = ["Yo! "]
output = ''.join(new_input)
return output
print hellohello("why is this not printing more yo")
到目前为止我只得到:
How's it going? Yo!
【问题讨论】:
-
new_input[3:] = ["Yo! "]不会将“从 3 开始的每个值”分配给字符串"Yo! ",它只是用单个条目替换从 3 开始的所有条目,而不是您需要创建new_input[3:] = ["Yo! "] * (len(new_input)-3)或类似的重复条目。
标签: python list python-2.7 replace