2024-03-29 04:52:31 发布
网友
计算字符串中字符出现次数的最简单方法是什么?
例如,计算'a'出现在'Mary had a little lamb'中的次数
'a'
'Mary had a little lamb'
您可以使用count():
>>> 'Mary had a little lamb'.count('a') 4
正如其他答案所说,使用字符串方法count()可能是最简单的,但是如果您经常这样做,请查看collections.Counter:
from collections import Counter my_str = "Mary had a little lamb" counter = Counter(my_str) print counter['a']
str.count(sub[, start[, end]])Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
sub
[start, end]
start
end
>>> sentence = 'Mary had a little lamb' >>> sentence.count('a') 4
您可以使用count():
正如其他答案所说,使用字符串方法count()可能是最简单的,但是如果您经常这样做,请查看collections.Counter:
相关问题 更多 >
编程相关推荐