使用python统计字符串中重复字符个数
时间: 2024-05-13 13:20:10 浏览: 99
python统计字符串中指定字符出现次数的方法
5星 · 资源好评率100%
可以使用字典来记录每个字符出现的次数,然后遍历字符串并更新字典。最后,将字典中值大于1的键值对统计即可。下面是示例代码:
```python
def count_duplicate_chars(s):
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
count = 0
for k, v in freq.items():
if v > 1:
count += 1
return count
```
使用示例:
```python
s = "hello world"
duplicate_count = count_duplicate_chars(s)
print(f"There are {duplicate_count} duplicate characters in '{s}'")
# 输出:There are 3 duplicate characters in 'hello world'
```
阅读全文