問題描述
我正在嘗試測試某個數字的十進制表示是否至少包含兩次數字 9,所以我決定這樣做:
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")
但 Python 總是以TypeError: Can't convert 'int' object to str implicitly"響應.
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?
推薦答案
你的問題在這里:
string.replace(9, '', 1)
您需要將 9
設為字符串文字,而不是整數:
You need to make 9
a string literal, rather than an integer:
string.replace('9', '', 1)
至于計算字符串中 9
出現次數的更好方法,請使用 str.count()
:
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
>>>
這篇關于“無法將'int'對象隱式轉換為str"錯誤(Python)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!