Sunday 18 December 2016

python - Count the number occurrences of a character in a string



What's the simplest way to count the number of occurrences of a character in a string?



e.g. count the number of times 'a' appears in 'Mary had a little lamb'


Answer




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.




>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...