Home Ask Login Register

Developers Planet

Your answer is one click away!

Evantf February 2016

compute character frequencies in Python strings

I was wondering if there is a way in Python 3.5 to check if a string contains a certain symbol. Also I'd like to know if there is a way to check the amount the string contains. For example, if I want to check how many times the character '$' appears in this string... ^$@%#$$, how would I do that?


Prune February 2016

These are the built-in functions index and count. You can find full documentation at the official site. Please get used to doing the research on your own; the first step is to get familiar with the names of the language elements.

if my_str.index('$') != 0:
    # Found a dollar sign

print my_str.count('$')

minitoto February 2016

You can use split to check if symbol's in the string:

if your_str.split('$'):

You can also use re.findall:

import re
print(len(re.findall('\$', your_str)))

It returns 0 if there is no such a symbol in the string, otherwise returns count of that symbol in the string.

But the easiest way is to check and return count if symbol is in:


It returns 0 if nothing is found.

Post Status

Asked in February 2016
Viewed 2,487 times
Voted 9
Answered 2 times


Leave an answer

Quote of the day: live life