我有一个字符串
string = 'AAA'
当使用string.count('A')
时,输出等于3
如果是 string.count('AA')
则输出等于 1
但是,字符串中有 2 个 'AA'。
是否有任何方法可以使用字典函数来计算上述重复字符串的数量?
我想听听您的有用建议。
提前谢谢大家。
最佳答案
问题是 Count 返回字符串中子字符串 sub 出现(非重叠)的次数。
试试这个,正如你在 post 中看到的那样:
def occurrences(string, sub):
count = start = 0
while True:
start = string.find(sub, start) + 1
if start > 0:
count+=1
else:
return count
关于python 使用字典函数计算字符串中的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19312556/