简体   繁体   中英

How do I write a function that accepts a string and will return a total number of certain characters in the string, without using .count?

beginner here. Trying to figure out how I can define a function that counts the total number of occurrences of certain characters in a string. Say, we want to count the number of occurrences of the letters a and b. I need to do it within a for loop. What I have so far is this. Please let me know what I can do to make this work!

#define functions 
def ch_count(word):
  total=0
  for letter in word:
    if letter==L1:
      total=total+1
  return total
#main program
L1=["a","e","y"]
print(ch_count("Merry Christmas")

You can try using a default dictionary. Unlike a normal dictionary, it provides a default value is a key does not exist in a dictionary.

from collections import defaultdict

string = 'quick brown fox'

letter_count = defaultdict(int)

for letter in string:
  letter_count[letter] += 1

print(letter_count)

You can use sum :

string = 'Some test string'
c = 'a'
sum(x == c for x in string)

Checking for multiple characters instead:

c = 'abc'
sum(x in c for x in string)

Or you can use collections.Counter to find the count of each character:

from collections import Counter
counts = Counter(string)
counts[letter]

you could write a function which takes 2 arguments. The string to check, and the letter that we want to use to count occurrencies in the string.

# I will use a as a default letter
def count_occurrencies(s, letter='a'):
    return sum([i == letter for i in s])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM