0

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']

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

3 Answers3

2

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))
2

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)
Michael M.
  • 10,486
  • 9
  • 18
  • 34
2

Do not split the text.

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

basket = []
for fruits in market:
    if fruits in text:
        basket.append(fruits)
print(basket)

And also there is an alternating way to obtain the same result in just one line.

common = list(filter(lambda x:x in text, market))
print(common)
Kavindu Nilshan
  • 569
  • 6
  • 17