在Python中,给字符串计数可以通过以下几种方法实现:
1. 使用`count()`方法:
s = 'Hello World!'
count = s.count('l')
print(count) 输出:3
2. 使用`for`循环遍历字符串:
s = 'Hello World!'
count = 0
for ch in s:
if ch == 'l':
count += 1
print(count) 输出:3
3. 使用`Counter`模块:
from collections import Counter
s = 'Hello World!'
count = Counter(s)['l']
print(count) 输出:3
4. 使用`re`模块的`findall`方法:
import re
s = 'Hello World!'
count = len(re.findall('l', s))
print(count) 输出:3