“无法将 'int' 对象隐式转换为 str"错误(Python) [英] "Can't convert 'int' object to str implicitly" error (Python)

查看:35
本文介绍了“无法将 'int' 对象隐式转换为 str"错误(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试某个数字的十进制表示是否至少包含数字 9 两次,所以我决定做这样的事情:

i=98759102字符串=str(i)if '9' in string.replace(9, '', 1): print("y")否则:打印(n")

但是 Python 总是以TypeError: Can't convert 'int' object to str隐式"作为响应.

我在这里做错了什么?是否真的有更聪明的方法来检测某个数字在整数的十进制表示中包含的频率?

解决方案

你的问题在这里:

string.replace(9, '', 1)

您需要使 9 成为字符串文字,而不是整数:

string.replace('9', '', 1)

为了更好地计算字符串中 9 的出现次数,请使用 str.count():

<预><代码>>>>我 = 98759102>>>字符串 = str(i)>>>>>>如果 string.count('9') >2:打印('是')别的:打印('否')不>>>

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?

解决方案

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

这篇关于“无法将 'int' 对象隐式转换为 str"错误(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆