python - Count occurrences of a letter in a string -
i'm trying count occurrences of letters in sting. got part python that, however, want doesn't count letter twice if occurs twice.
so, "my name", should give string '21111', instead of '211121' (so not counting both of m's twice).
the code far is:
for char in tested_str2: if char in 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz': x = tested_str2.count(char) percentage = percentage + str(x)
you can use collections.counter
, set
:
>>> collections import counter >>> strs = ''.join(x x in "my name" if x.isalpha()).lower() >>> c = counter(strs) >>> seen = set() >>> ''.join(str(c[item]) item in strs if item not in seen , not seen.add(item)) '21111'
as suggested @dsm, instead of using set
can use collections.ordereddict
:
>>> collections import ordereddict >>> ''.join(str(c[item]) item in ordereddict.fromkeys(strs)) '21111'
Comments
Post a Comment