0

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!
Shubham Sharma
  • 1,753
  • 15
  • 24
  • 1
    `new_input[3:] = ["Yo! "]` doesn't assign "every value from 3 on" to the string `"Yo! "`, it just replaces all the entries from 3 on with the single entry, instead you would need to create the duplicate entries like `new_input[3:] = ["Yo! "] * (len(new_input)-3)` or similar. – Tadhg McDonald-Jensen Jun 20 '16 at 16:30
  • Please Read [Explain Python's slice notation](http://stackoverflow.com/q/509211) – Bhargav Rao Jun 20 '16 at 16:35
  • Please [accept](http://meta.stackexchange.com/questions/5234) an answer if you think it solves your problem. It will community at large to recognize the correct solution. This can be done by clicking the green check mark next to the answer. See this [image](http://i.stack.imgur.com/uqJeW.png) for reference. Cheers. – Bhargav Rao Jun 20 '16 at 18:02

2 Answers2

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']

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • It'd be helpful if you could explain the diff between `split()` and `split(' ')`. Though a simple issue, Many of the users don't know this. – Bhargav Rao Jun 20 '16 at 16:44
  • 1
    @BhargavRao -- Sure, added a footnote since it is sort of tangent to the purpose of the rest of the post. – mgilson Jun 20 '16 at 16:50
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]

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
advance512
  • 1,327
  • 8
  • 20
  • 1
    you know you can just do `xrange(3, len(new_input))` instead of slicing then adding 3 to the index each time. Also please add description to what you changed and why you changed it or this won't help the op understand what went wrong / how to fix it themselves next time. – Tadhg McDonald-Jensen Jun 20 '16 at 16:33
  • I updated solution based on correct remark by @TadhgMcDonald-Jensen that using slices and index calculus is not necessary. Also added explanation of what went wrong before. Not sure why down voted - this does what it is required to do by OP. – advance512 Jun 20 '16 at 16:40
  • I imagine @ShubhamSharma probably downvoted because posting a whole code block with only 1-4 lines changed without comments or explanation is very rarely helpful. Now that there is an explanation it doesn't really fit that anymore. – Tadhg McDonald-Jensen Jun 20 '16 at 16:45
  • yes, but now i remove my downvote @TadhgMcDonald-Jensen – Shubham Sharma Jun 20 '16 at 16:48
  • 1
    Thank you so much!! – sunnysid3up Jun 20 '16 at 17:06