python中统计字符串个数
时间: 2023-08-27 19:04:08 浏览: 38
你可以使用count()方法来统计一个字符串中某个子字符串出现的次数。比如,如果你想统计字符串s中子字符串sub出现的次数,你可以这样做:
```
s = "hello world"
sub = "l"
count = s.count(sub)
print(count)
```
这将输出字符串s中子字符串"l"出现的次数,即3。如果你想统计字符串s中不同子字符串出现的次数,你可以使用Python中的collections模块中的Counter类来实现。例如:
```
from collections import Counter
s = "hello world"
c = Counter(s)
print(c)
```
这将输出一个Counter对象,其中包含了字符串s中每个字符出现的次数。
相关问题
python统计字符串中字符个数
好的,问题收到。下面是Python统计字符串中字符个数的代码实现:
```python
string = input("请输入字符串:") # 输入字符串
char_count = {} # 创建一个空字典
for char in string: # 遍历字符串中的每个字符
if char in char_count: # 如果字符已经在字典中,计数加1
char_count[char] += 1
else: # 如果字符不在字典中,添加键值对并计数为1
char_count[char] = 1
print("各字符出现次数为:")
for key, value in char_count.items(): # 遍历字典中的所有键值对
print(key, ":", value) # 输出键和对应的值
```
运行程序后,输入一个字符串,程序会输出该字符串中每个字符出现的次数。希望我的回答能够帮助到你!
python统计字符串中字母个数
你可以使用 Python 中的 `collections` 模块中的 `Counter` 类来统计字符串中字母的个数。下面是一个例子:
```python
from collections import Counter
string = "Hello, world!"
letter_count = Counter(filter(str.isalpha, string.lower()))
print(letter_count)
```
输出:
```
Counter({'l': 3, 'o': 2, 'e': 1, 'h': 1, 'w': 1, 'r': 1, 'd': 1})
```
在上述代码中,我们首先使用 `filter` 函数过滤出所有的字母,并将它们转换为小写。然后,我们使用 `Counter` 类来计算每个字母出现的次数。最后,我们打印出计数器对象 `letter_count` 的内容。