Replace every word after index k in list

2019-09-13 07:16发布

问题:

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!

回答1:

Try this:

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")

Output:

How's it going? Yo! Yo! Yo! Yo!
How's it going?
How's it going? Yo!

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.

[edit: updated solution based on correct remark that using slices and index calculus is not necessary, also added explanation of what went wrong before]



回答2:

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?"] ...

>>> s = "My name is bla bla bla?"
>>> new_input = s.split()
>>> output = ['Yo!'] * len(new_input)
>>> output[:3] = ["How's", "it", "going?"]
>>> output
["How's", 'it', 'going?', 'Yo!', 'Yo!', 'Yo!']

The problem with your code is this line:

new_input[3:] = ["Yo! "]

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 of s.split(' '). s.split() is the same thing as s.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']