计算字符串(Python)中某些字符的出现次数的首选方法是什么? [英] What is the preferred way to count number of ocurrances of certain character in string (Python)?
问题描述
如何在没有 str.count()
的情况下执行此操作,因为它在Python v2.7.3文档中被列为弃用?
我无法找到我应该用的东西。
使用 str.count()
- 它不被列为弃用。 ( Python 2.7.3 , Python 3.2.3 - 两者都没有关于被弃用的注释)。
>>> test.count(t)
2
我假定你的意思是 string.count()
- 其中 $ b
区别在于 str.count()
是一个字符串对象的方法。方法,而 string.count()
是字符串
模块中的一个函数。
>>> test.count(t)
2
>>>导入字符串
>>> string.count(test,t)
2
很明显,为什么后者已被弃用(并在3.x中被删除)而转为前者。
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.
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.
这篇关于计算字符串(Python)中某些字符的出现次数的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!