Using count() for finding multiple characters in a string
Question:
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!
Answers:
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}
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’]
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!
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}
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’]