1

New to Python.

Say I wanted to get the total number of '.' or '!' in a body of text, what is the 'pythonic' way of doing so? I'd think there would be something like: text.count(LIST)

I realize the below would work, but wondering what the python people think.

for char in list(text):
    if char in LIST:
        sum += 1
k_clark.90
  • 27
  • 4
  • Does this answer your question? [Count number of occurrences of a substring in a string](https://stackoverflow.com/questions/8899905/count-number-of-occurrences-of-a-substring-in-a-string) Then you could just add the numbers of occurrences of `.` and `!` up. – no ai please Oct 10 '21 at 00:07
  • `total = text.count('.') + text.count('!')` works but seems a bit inelegant to me – k_clark.90 Oct 10 '21 at 00:14
  • 2
    you want something like `counts = collections.Counter(text); total = sum(counts[c] for c in LIST)` – juanpa.arrivillaga Oct 10 '21 at 01:51

0 Answers0