2

I am trying to test if the decimal representation of a certain number contains the digit 9 at least twice, so I decided to do something like that:

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

But Python always responds with "TypeError: Can't convert 'int' object to str implicitly".

What am I doing wrong here? Is there actually a smarter method to detect how often a certain digit is contained in the decimal representation of an integer?

2
  • 2
    string.replace('9', '', 1) (note the single quotes around 9). Also, there is: string.count('9') Commented Jul 16, 2017 at 21:06
  • 1
    str(i).count('9') > 1 Commented Jul 16, 2017 at 21:08

2 Answers 2

1

Your problem is here:

string.replace(9, '', 1)

You need to make 9 a string literal, rather than an integer:

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

As for a better way to count the occurrences of 9 in your string, use str.count():

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


no
>>>
Sign up to request clarification or add additional context in comments.

Comments

-1

You need quotes around the nine.

2 Comments

Mine was first. Look at the time. You could say that the other answer was already given by this one, because it came after mine. Since SO puts most upvoted answers at the top, it looks like the other one came first.
Im sorry i didnt properly check the time these answers were posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.