The Python Oracle

Count the number of occurrences of a character in a string

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Count The Number Of Occurrences Of A Character In A String
00:16 Answer 1 Score 61
00:26 Accepted Answer Score 1814
00:46 Answer 3 Score 197
00:55 Answer 4 Score 37
01:14 Thank you

--

Full question
https://stackoverflow.com/questions/1155...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #count

#avk47



ACCEPTED ANSWER

Score 1814


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



ANSWER 2

Score 197


You can use .count() :

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



ANSWER 3

Score 61


Regular expressions maybe?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))



ANSWER 4

Score 37


Python-3.x:

"aabc".count("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.