问题描述
我正在尝试测试某个数字的十进制表示是否至少包含两次数字 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 >>>