“Can't convert 'int' object to str implicitly” error (Python)

后端 未结 2 865
余生分开走
余生分开走 2020-12-21 09:33

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         


        
相关标签:
2条回答
  • 2020-12-21 10:05

    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
    >>>
    
    0 讨论(0)
  • 2020-12-21 10:16

    You need quotes around the nine.

    0 讨论(0)
提交回复
热议问题