Search code examples
pythonstringsplitsegment

how to split a string into diferent segments of 2 words where the first word of the second segment repeats the last word of the first


I am trying to figure out how to split a string into segments of 2 words where the first word of the second segment repeats the last word of the first. (in Python 2)For example, "hi i am a human named joe norman" should slit into "hi i", "i am", "am joe", "joe norman". I have the following code:

txt = raw_input("")

newtxt = txt.split(" ")

the problem with this is that it splits txt by each space, not every other. I would like to use no libraries. Thank you.


Solution

  • Use zip:

    t = "hi i am a human named joe norman"
    words = t.split()
    
    result = list(zip(words, words[1:]))
    
    for first, second in result:
        print("{} {}".format(first, second))
    

    Output

    hi i
    i am
    am a
    a human
    human named
    named joe
    joe norman