You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何统计字符串内多个不同字符的出现次数?

How to Count Occurrences of Multiple Specific Characters in a String

Great question! Let's walk through how to solve this using Python, since your initial example uses the str.count() method.

Approach 1: Loop Through Target Characters (Simple & Straightforward)

If you want to stick close to the count() method you already know, you can iterate over each character in your reference string ("awesome") and calculate its count in the target string one by one. We'll store the results in a dictionary for easy readability.

Here's the code:

# Your target string
target_str = "Simple Example"
# The characters you want to count (from "awesome")
chars_to_track = "awesome"

# Initialize an empty dictionary to hold counts
char_counts = {}

# Loop through each character in our reference string
for char in chars_to_track:
    # Calculate count and add to the dictionary
    char_counts[char] = target_str.count(char)

# Print the results
print(char_counts)

Output:

{'a': 0, 'w': 0, 'e': 2, 's': 1, 'o': 0, 'm': 2}

Note on Case Sensitivity

Notice in the example above, the uppercase E in "Example" gets counted because count() is case-sensitive. If you want to ignore case (e.g., count both E and e as the same character), modify the code to normalize both strings to lowercase (or uppercase):

for char in chars_to_track:
    char_counts[char] = target_str.lower().count(char.lower())

Approach 2: Use collections.Counter (More Efficient for Large Strings)

If your target string is very long, calling count() multiple times (once per character) can be inefficient—it has to scan the entire string each time. Instead, use Python's built-in Counter class to count all characters in one pass, then extract the counts you care about.

from collections import Counter

# Count all characters in the target string first
total_char_counts = Counter(target_str)

# Extract counts only for characters in "awesome"
char_counts = {char: total_char_counts.get(char, 0) for char in chars_to_track}

print(char_counts)

This gives the same result as Approach 1, but only scans the target string once—much better for performance with large datasets.

Which Approach Should You Use?

  • Use Approach 1 for small strings or when you only need to count a handful of characters—it's simple and easy to read.
  • Use Approach 2 for large strings or when you need to count many characters—it's more efficient.

内容的提问来源于stack exchange,提问作者Reuben Royal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:48:12