How do you replace every word after index[3] in list?
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!
Call me lazy, but I'd probably first create a list of length
len(new_input)
full of'Yo!'
and then swap in the["How's", "it", "going?"]
...The problem with your code is this line:
You're replacing multiple elements with a single element. You could probably fix the code by doing
new_input[3:] = ["Yo! "] * (len(new_input) - 3)
which would create a list of"Yo! "
that is the same length as the sublist that you're trying to replace.You may have noticed that I used
s.split()
instead ofs.split(' ')
.s.split()
is the same thing ass.split(None)
which splits on consecutive runs of whitespace (including newlines and tabs). Basically,'foo bar\tbaz'.split()
results in['foo', 'bar', 'baz']
whereas'foo bar\tbaz'.split(' ')
would result in['foo', '', 'bar\tbaz']
Try this:
Output:
By executing
new_input[3:] = ["Yo! "]
, you simply replaced the subarray of all string tokens (in the array separated bysplit
) 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.[edit: updated solution based on correct remark that using slices and index calculus is not necessary, also added explanation of what went wrong before]