什么是统计字符串(Python)的某些字符ocurrances数量的首选方法是什么?(What is

2019-07-29 05:29发布

如何做到这一点没有str.count()因为它被列为的Python v2.7.3文档中弃用?

我无法找到我应该使用。

Answer 1:

使用str.count() -它不列为弃用。

( Python的2.7.3 , Python的3.2.3 -既没有关于被废弃的笔记)。

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

我会想你的意思string.count() -这是有利于对String对象的方法计提折旧。

不同的是, str.count()是在字符串对象的方法,而string.count()是在一个功能string模块。

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

为什么后者赞成前者被弃用(和3.X删除)很明显。



Answer 2:

使用len()

>>> len('abcd')
4


Answer 3:

这在2.7.3工作正常

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


Answer 4:

不使用计数,你可以这样做:

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

结果:

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


Answer 5:

另一种方法可以

strs.__len__()



文章来源: What is the preferred way to count number of ocurrances of certain character in string (Python)?