What is the preferred way to count number of ocurrances of certain character in string (Python)?

拥有回忆 提交于 2019-12-20 03:46:10

问题


How do I do this without str.count(), because it is listed as deprecated in Python v2.7.3 documentation?

I am unable to find what I should use instead.


回答1:


Use str.count() - it's not listed as deprecated.

(Python 2.7.3, Python 3.2.3 - both have no notes about being deprecated).

>>> "test".count("t")
2

I'll presume you meant string.count() - which is depreciated in favour of the method on string objects.

The difference is that str.count() is a method on string objects, while string.count() is a function in the string module.

>>> "test".count("t")
2
>>> import string
>>> string.count("test", "t")
2

It's clear why the latter has been deprecated (and removed in 3.x) in favour of the former.




回答2:


Use len():

>>> len('abcd')
4



回答3:


This works fine in 2.7.3

>>> strs='aabbccddaa'
>>> strs.count('a')
4



回答4:


Without using count you can do this:

def my_count(my_string, key_char):
    return sum(c == key_char for c in my_string)

Result:

>>> my_count('acavddgaaa','a')
5



回答5:


The other way can be

strs.__len__()



来源:https://stackoverflow.com/questions/10385902/what-is-the-preferred-way-to-count-number-of-ocurrances-of-certain-character-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!