统计Python中字符串中出现的次数
在Python中,可以使用内置的count()
方法来统计字符串中某个字符或子串出现的次数。
例如,统计字符串s
中字符a
出现的次数:
s = "aabbcdaa"
char_to_count = "a"
count = s.count(char_to_count)
print(f"{char_to_count} appears {count} times.")
如果要统计字符串中子串sub
出现的次数:
s = "aabbcdaa"
sub = "aa"
count = s.count(sub)
print(f"{sub} appears {count} times.")
这两段代码会分别输出:
a appears 4 times.
aa appears 2 times.
评论已关闭