Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way to count the number of ocurrences of a certain character in a string?

Tags:

python

string

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

I am unable to find what I should use instead.

EDIT: The question originally stated that str.count() was deprecated but that is incorrect and misleading. See https://stackoverflow.com/a/10385996/966508 for explanation

like image 240
varesa Avatar asked Nov 29 '22 09:11

varesa


1 Answers

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.

like image 95
Gareth Latty Avatar answered Dec 06 '22 10:12

Gareth Latty