[Tutor] String module; Count

Ben Sherman bensherman at gmail.com
Wed Oct 17 23:02:56 CEST 2007

You can only count one at a time.

count = conversion(n).count("0") + conversion(n).count("1")

count is a string method, so it operates directly on the string - you
don't have to call it like you did.

import string
string.count(mystr, "cheese")

is the same as


At least it is in newer versions of python.

Let me know if that helped.


On 10/17/07, ddm2 at sfu.ca <ddm2 at sfu.ca> wrote:
> I am having trouble getting the string.count function to work. I want it to
> count the amount of digits (0 or 1) in the string, but I keep getting an
> error stating the string.count was expecting a character buffer object.
> count = string.count(conversion(n),["0","1"])
> Traceback (most recent call last):
>   File "/Users/<name>/Desktop/Project 1.py", line 59, in -toplevel-
>     signed_mag()
>   File "/Users/<name>/Desktop/Project 1.py", line 29, in signed_mag
>     count = string.count(conversion(n),["0","1"])
>   File
> "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/string.py"
> , line 348, in count
>     return s.count(*args)
> TypeError: expected a character buffer object
> I'm trying to make a decimal to binary converter that has the option to
> select the amount of bits for Signed Binary. I've thought of a way (not
> tested yet) on how to implement the bits, but I first need to count the
> amount of digits in the original conversion. Thanks in advance.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list