Counting Characters in a String

Asked 1 years ago, Updated 1 years ago, 84 views

I'd like to count how many specific characters appear in the string. What's the easiest way?

ex) mystring = "aaabcc" When

a->3 b->1 c->2

string python count

2022-09-22 22:31

1 Answers

Write str.count(sub[, start[, end]).

Returns the strong result of sub within the range of [start, end].

m = "kkkkaa"

print "m.count('kk'):\t\t", m.count("kk")
print "m.count('a'):\t\t", m.count("a")
print "m.count('a', 0, 2):", m.count("a", 0, 2)

Result:

m.count('kk'):      2
m.count('a'):       2
m.count('a', 0, 2): 0


2022-09-22 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.