替换列表中索引k之后的每个单词 [英] Replace every word after index k in list
问题描述
如何替换列表中索引[3]之后的每个单词?
How do you replace every word after index[3] in list?
例如,我需要将第一个单词更改为"how's",将第二个单词更改为"it",将第三个单词更改为"going?".然后,我需要将索引[3]之后的每个单词更改为"yo":
For example, I need to change first word to "How's" and second word to "it" and third word to "going?". Then, I need to change every word to "yo" after index[3]:
input = "My name is bla bla bla?"
output = "How's it going? Yo! Yo! Yo!"
这是我到目前为止所拥有的:
This is what I have so far:
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")
到目前为止,我只得到:
So far I only get:
How's it going? 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?"
for currentIndex in xrange(3, len(new_input)):
new_input[currentIndex] = "Yo!"
output = ' '.join(new_input)
return output
print hellohello("why is this not printing more yo")
print hellohello("why is this")
print hellohello("why is this yep")
输出:
How's it going? Yo! Yo! Yo! Yo!
How's it going?
How's it going? Yo!
通过执行new_input[3:] = ["Yo! "]
,您只需用单个字符串"Yo!"替换从索引3到最后一个索引的所有字符串标记的子数组(在由split
分隔的数组中),而不是替换每个数组项目本身.基本上,您引用了数组的整个切片(3:
)而不是单个项目.
By executing new_input[3:] = ["Yo! "]
, you simply replaced the subarray of all string tokens (in the array separated by split
) from index 3 to the last index with a single string, "Yo!", instead of replacing each array item by itself. Basically, you referenced an entire slice of the array (3:
) instead of just a single item.
这篇关于替换列表中索引k之后的每个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!