Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
803 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
>>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...