Python-将INT的数据类型更改为Str不起作用
每当我运行代码时,都会出现一个错误,其中指出“ typeError:只能串联str(不是“ int”)to str“这在output = output = output + text.yellow + numbers
line中。我知道我不能用字符串添加整数,为此,我也在行之前更改了类型,但是它似乎不起作用,我无法理解错误是什么以及如何解决该问题,HEP会是真的很感谢
我的代码如下:
信息: text.yellow
是一种类属性,只需将文本更改为黄色。 abile_numbers and chosos_numbers是一个列表
def print_board():
number = 1
output = ""
while number < 91:
if number in available_numbers:
str(number)
output = output + text.yellow + number
int(number)
elif number in choosen_numbers:
str(number)
output = output + text.green + number
int(number)
number += 1
print(output)
Whenever I run my code an error comes which states "TypeError: can only concatenate str (not "int") to str" this comes in the output = output + text.yellow + number
line. I understand thati can't add an integer with a string and for that I have also changed its type just before the line but it doesn't seem to work and I cant understand what the error is and how to solve it, hep would be really appreciated
My code is as below:
Info:
The text.yellow
is a class attribute which just changes the text to yellow color.
available_numbers and choosen_numbers is a list
def print_board():
number = 1
output = ""
while number < 91:
if number in available_numbers:
str(number)
output = output + text.yellow + number
int(number)
elif number in choosen_numbers:
str(number)
output = output + text.green + number
int(number)
number += 1
print(output)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试一下:
Try this:
确切地说,您可以将整数转换为字符串,但不幸的是,您无法将其保存在任何地方。
这样做
或
这个
而不是
Precisely you can convert integer to string but unfortunately, you cannot save it anywhere.
Do this
or
this
instead of this
您无需每次需要更改它的类型。您可以在需要时更改类型,而不必更改它))))
You don't need to change the type every time when you need to change it. You can change the type at the moment when you need it and don't have to change it back))
您应该存储
str(number)
和int(number)
number 变量,如果您想实际更改numbern
。但是无论如何,您应该使用f弦或格式来cont int int int int and contrings:
以防万一您仍然想使用
+
进行格式化,您应该执行以下操作:确保
text.yellow
也是strYou should store
str(number)
andint(number)
into thenumber
variable if you want to actually changenumber
.But anyway, you should use f-string or format in order to concat int and strings, for example:
just in case you still want to format it using
+
, you should do something like:make sure that
text.yellow
is also a str变量数仍然是整数。而不是尝试以下:
output = output + text.green + str(number)
或将字符串版本存储在类似的变量中用于串联The variable number is still an integer. Try this instead:
output = output + text.green + str(number)
or store the string version in a variable like thisstring_number = str(number)
and use that variable for concatenation