Home > OS >  combine last word in a string with each of the preceding words
combine last word in a string with each of the preceding words

Time:10-31

I have a multi-line string

words = """anticipated, unlikely, preferable, accidental, haphazard result
team members, student, bride    reluctant"""

where the last word is separated from the second last word with a tab, NOT a comma

i.e. "anticipated, unlikely, preferable, accidental, haphazard\tresult"

each line in the mutli-line string has a different amount of words in it

I want to print out a result from each line like this where the last word is combined with each preceding word:

anticipated result
unlikely result
preferable result
accidental result
haphazard result
reluctant team members
reluctant students
reluctant bride

sorry, I couldn't come up with any code after experimenting with splitting and dictionary paths.

CodePudding user response:

words = """anticipated, unlikely, preferable, accidental, haphazard\tresult
team members, student, bride\treluctant"""

for line in words.split('\n'):
    word_list_str, last_word = line.split('\t')
    word_list = word_list_str.split(',')
    for word in word_list:
        # use this if the last word should be at the beginning
        print(f'{last_word} {word.strip()}')
        # use this if the last word should be at the end
        print(f'{word.strip()} {last_word}')

CodePudding user response:

You can do this in a comprehension by gradually isolating the parts with the appropriate split separator:

words = """anticipated, unlikely, preferable, accidental, haphazard\tresult
team members, student, bride\treluctant"""

pairings = ( f"{left} {right}"                         # pair up left&right
             for line in words.split('\n')             # get each line
             for leftList,right in [line.split('\t')]  # isolate right side
             for left in leftList.split(', '))         # extract each left side

print(*pairings,sep='\n')

anticipated result
unlikely result
preferable result
accidental result
haphazard result
team members reluctant
student reluctant
bride reluctant
  • Related