Home > OS >  Python how to select some string from sentence
Python how to select some string from sentence

Time:10-05

I try to select some text in the list to create a new list but the text sticks together

market = ['cherry','apple','orange','mango','banana']
text = 'Iwanttobuyanapple mango orange andbanana'
new_text = text.split()
basket = []
for fruits in new_text:
    if fruits in market:
        basket.append(fruits)
print(basket)

The result is ['mango', 'orange'] but i want this ['apple, 'mango', 'orange', 'banana']

CodePudding user response:

You can search the other way round and look for the "market"items in the text.

market = ['cherry', 'apple', 'orange', 'mango', 'banana']
text = 'Iwanttobuyanapple mango orange andbanana'


def find_fruit(text, market):
    fruit = []
    for item in market:
        if item in text:
            fruit.append(item)
    return fruit

print(find_fruit(text, market))

CodePudding user response:

Using split() won't work because the strings aren't delimited by space. Instead, check for substrings.

market = ['cherry', 'apple', 'orange', 'mango', 'banana']
text = 'Iwanttobuyanapple mango orange andbanana'
basket = []
for fruit in market:
    if fruit in text:
        basket.append(fruit)
print(basket)
  • Related