在 Python 中用一个字符串和一个整数创建一个字符串
问题描述
我在尝试获取一个整数并在其前面加上b"并将其转换为字符串时收到此错误:
I get this error when trying to take an integer and prepend "b" to it, converting it into a string:
File "program.py", line 19, in getname
name = "b" + num
TypeError: Can't convert 'int' object to str implicitly
这和这个功能有关:
num = random.randint(1,25)
name = "b" + num
解决方案
name = 'b' + str(num)
或
name = 'b%s' % num
正如 S.Lott 所指出的,混合运算符 '%' 在 Python 3 及更高版本中已弃用.我从 INTERCAL 偷了混合"这个名字,但这就是我谈论它的方式想要至少在印刷版中看到它一次 - 就像渡渡鸟一样 - 它从地球上消失了.
as S.Lott notes, the mingle operator '%' is deprecated for Python 3 and up. And I stole the name "mingle" from INTERCAL but that's how I talk about it and wanted to see it in print at least once before - like the dodo - it vanishes from the face of the earth.
相关文章