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

3. 使用`Counter`模块:
from collections import Counters = 'Hello World!'count = Counter(s)['l']print(count) 输出:3
4. 使用`re`模块的`findall`方法:
import res = 'Hello World!'count = len(re.findall('l', s))print(count) 输出:3
