quot;Can#39;t convert #39;int#39; object to str implicitlyquot; error (Python)(“无法将int对象隐式转换为str错误(Python))
问题描述
我正在尝试测试某个数字的十进制表示是否至少包含两次数字 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“无法将'int'对象隐式转换为str"错误(Python)
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
