"Unable to convert object" int "to str implicitly" error (Python)

I'm trying to check if the decimal representation of a certain number contains the digit 9 at least twice, so I decided to do something like this:

i=98759102
string=str(i)
if '9' in string.replace(9, '', 1): print("y")
else: print("n")

      

But Python always responds "TypeError: Unable to convert object" int "to str implicitly".

What am I doing wrong here? Is there a smarter method for determining how often a particular digit is contained in the decimal representation of an integer?

+3


source to share


2 answers


Your problem is here:

string.replace(9, '', 1)

      

You need to do a 9

string literal, not an integer:



string.replace('9', '', 1)

      

For the best way to count occurrences 9

in your string, use str.count()

:

>>> i = 98759102
>>> string = str(i)
>>> 
>>> if string.count('9') > 2:
    print('yes')
else:
    print('no')


no
>>>

      

+2


source


You need quotes around nine.



0


source







All Articles