Search code examples
pythonsplitfindall

How to select certain text between other text in python?


Here is an example string:

text = "hello, i like to eat beef 'sandwiches' and beef 'jerky' and chicken 'patties' and chicken 'burgers' and also chicken 'fingers' and other chicken 'meat' too."

I am trying to separate the words "patties", "burgers", fingers", and "meat" from this text. I want to separate the words after chicken but before the closing quotation.

I have gotten stumped on how to even separate a single one. I can split after "chicken ' but then how can i select the text up until the next ' ?

I would like to iterate through a list to save the variables to an array. Thanks for any help you can provide.


Solution

  • You can use regular expressions:

    import re
    
    text = "hello, i like to eat beef 'sandwiches' and beef 'jerky' and chicken 'patties' and chicken 'burgers' and also chicken 'fingers' and other chicken 'meat' too."
    
    match = re.findall(r'chicken \'(\S+)\'', text)
    print (match)
    

    Outputs:

    ['patties', 'burgers', 'fingers', 'meat']