Home > other >  Count total list elements in a string
Count total list elements in a string

Time:10-06

I ran into a problem I couldn't solve or find a solution to online and was hoping someone on here might have the answer. I'm trying to count the number of list elements in a string. I've tried the usual ways like count, isinstance, and set(probably all wrong)

I would like to count how many list elements I have in str1:

arr = [1, 'apple', 'banana', 2, 3]
str1 = ("this "   arr[0]   " then "   arr[3]   " next "   arr[2])

The output would look something like this: arr[] was used "3" times in str1

:edit: When trying to count list elements in a string, syntax to count must change:

str1 = ("this " str(arr[0]) " then " str(arr[2]) " next " str(arr[3])) With the answer below this solves the problem for my issue.

CodePudding user response:

Use the count() method to count how many times a substring occurs in a string. And use sum() to add up the counts of each list element.

total = sum(str1.count(str(i)) for i in arr)
print(f'Str1 contains a total of {total} arr[]')

This counts all the duplicate matches separately. If you don't need those separate counts, use in to test if the element is in the string.

total = sum(str(i) in str1 for i in arr)
  • Related