I am using Python count() function to find the number of times a character has been repeated in a string. e.g., "parya".count("a") --> 2 how can I use count for more that one character? i.e., "parya".count("a","y") --> 2,1 Thank you!
Asked
Active
Viewed 227 times
2 Answers
2
count()
can only count one thing at a time. If you want the counts of two strings, call it twice.
("parya".count("a"), "parya".count("y"))
If you want the counts of everything, use collections.Counter()
.
from collections import Counter
counts = collections.counter("parya")
This will return the dictionary
{"p": 1, "a": 2, "r": 1, "y": 1}

Barmar
- 741,623
- 53
- 500
- 612
0
You could do it as a list comprehension
my_string = 'parya'
print([f'{character}: {my_string.count(character)}' for character in {*my_string}])
Output:
['p: 1', 'y: 1', 'a: 2', 'r: 1']

Ovski
- 575
- 3
- 14