Home>
Purpose

masters1 = "Saito has a very beautiful hand"
ans = ['Saito is','hand','do']

I want to separate masters1 with the words contained in ans and output ['','very beautiful','','is']

What I tried
masters1 = "Saito has a very beautiful hand"
ans = ['Saito is','hand','do']
for a in ans:
    masters2 = masters1.split (a)
print (masters2)
---
#Output result
['Saito has a very beautiful hand','I have']


In this way, it doesn't work because there is a break only in the last'and'.
Please teach someone.

  • Answer # 1

    When the program expands the loop and replaces the variables with literals,

    masters2 = "Saito has a very beautiful hand" .split ('Saito is')
    masters2 = "Saito has a very beautiful hand" .split ('hand')
    masters2 = "Saito has a very beautiful hand" .split ('and')
    print (masters2)


    That's the result.

    If you say "separate by one of these", you will use a regular expression.
    |Is "or".

    import re
    masters1 = "Saito has a very beautiful hand"
    ans = ['Saito is','hand','do']
    masters2 = re.split ("|" .join (ans), masters1)
    print (masters2)