Ahmad bani
Ahmad bani

Reputation: 23

How to check if string contain list and show it in python

i have list: lst [a,b,c,d,e]

and then the input: food

i want the output : there is 1 d

another input example: aachen

so the output is: there is 2 a there is 1 e

and its doesnt matter the upppercase or lowercase.

Upvotes: 2

Views: 129

Answers (2)

wasif
wasif

Reputation: 15488

Python native way:

l = ['a','b','c','d','e']
m = {}
s = input("Enter input string:")
for f in l:
  for k in range(len(s)):
    if f == s[k]:
      if f in m:
        m[f] = m[f] + 1 
      else:
        m[f] = 1

for j in m.keys():
  print(s,"has")
  print(m[j],j)

Upvotes: 0

PacketLoss
PacketLoss

Reputation: 5746

You can use collections.Counter() to count the occurrences of each letter, then iterate over your lst and output the number of times each number occurred.

import collections

lst = ['a','b','c','d','e']

word = 'food'

word_count = collections.Counter(word)

for letter in lst:
    count = word_count.get(letter)
    if count:
        print(f"There is {count} {letter}")

Upvotes: 1

Related Questions