pythoy2.编写统计任给字符串中指定字符(串)的个数的函数statchars()
时间: 2023-05-18 18:00:28 浏览: 56
Python2中编写统计任意给定字符串中指定字符(串)的个数的函数statchars()可以通过以下方式实现。
首先,定义一个函数statchars(string, target),其中string表示需要统计的字符串,target表示需要统计的目标字符或者字符串。函数的具体实现如下:
```
def statchars(string, target):
count = 0
index = 0
while index < len(string):
if string[index: index + len(target)] == target:
count += 1
index += len(target)
else:
index += 1
return count
```
该函数运行的原理是,在字符串中逐个扫描字符或子字符串,如果与目标字符或子字符串匹配,则计数器加1,并将扫描位置跳过匹配的长度;否则,扫描位置继续向后移动1个字符。最终返回计数器的值即可。
例如,输入字符串"abcabcabc" 和 目标子字符串"abc",则函数statchars("abcabcabc", "abc")的返回值就是3,表示在给定字符串中出现了3个"abc"。对于其他的字符或子字符串,同样可以通过这个函数来统计出现次数。
需要注意的是,在Python3中,字符串的slice操作得到的结果是byte strings而不是unicode strings,因此如果在Python3中使用这个函数,需要将string和target都以byte string的形式传入,即:
```
def statchars(string, target):
count = 0
index = 0
while index < len(string):
if string[index: index + len(target)] == target:
count += 1
index += len(target)
else:
index += 1
return count
s = b"abcabcabc"
t = b"abc"
result = statchars(s, t)
print(result) # 输出:3
```