Home > Software engineering >  Count the string value, based on count print the value
Count the string value, based on count print the value

Time:02-02

I have a list:

a = ['the','is','the','for','who','the','which'].

I want to count the occurrence of 'the'. For example, here 'the' appears 3 times, so it will print: the1,the2,the3.

CodePudding user response:

You can use count method:

['the','is','the','for','who','the','which'].count('the')

In your case, you could do something like:

count = a.count('the')
print(",".join(f'the{idx   1}' for idx in range(count)))

CodePudding user response:

a = ['the','is','the','for','who','the','which']
result = [item   str(idx) for idx, item in enumerate(filter(lambda _: _ == "the", a), 1)]

CodePudding user response:

a=['the','is','the','for','who','the','which']
j=1
for val in a:
    if val == 'the':
        print(val   str(j))
        j =1

CodePudding user response:

I like to use regex for this, as this gives you more freedom when comparig strings. Since you also want to append the number of occurrences to a string, you might need a loop.

Here is my take on your question:

import re

a = ['the','is','the','for','who','the','which']

out = []

value = "the"
occur = 0

for input in a:
    result = re.search(value, input)
    if result:
        occur  = 1
        out.append(value   str(occur))

for output in out:
    print(output)

Changing the value variable will make your code try to match other strings (say "who"). You could also use the regex101 website to find best regex fits for all cases.

Below is the resulting outout:

the1
the2
the3
  •  Tags:  
  • Related