英文:
Hello I am trying to display "5 + 5 = 10" with the syntax as follows print ("2 + 2 = " + ( 2 + 2) )
问题
我正在尝试使用以下语法显示 "5 + 5 = 10"
:print ("2 + 2 = " + ( 2 + 2) )
,但是我一直收到错误信息:
" TypeError: must be str, not int"
感谢帮助
我尝试过:str ("2 + 2 = " + ( 2 + 2) )
英文:
I am trying to display "5 + 5 = 10"
with the syntax as follows print ("2 + 2 = " + ( 2 + 2) )
, what is the correct syntax to write it as i keep getting the error :
" TypeError: must be str, not int"
Appreciate the help
I tried : str ("2 + 2 = " + ( 2 + 2) )
答案1
得分: 4
没人建议使用 f-strings:
print(f'2 + 2 = {2 + 2}')
或者(自 Python 3.8 起):
print(f'{2 + 2 = }')
英文:
Nobody suggested the f-strings:
print(f'2 + 2 = {2 + 2}')
Or even (since python3.8):
print(f'{2 + 2 = }')
答案2
得分: 2
在Python中,它是不同的类型,你不能在str和int类型之间使用+运算符。对于你的情况,你可以按照以下方式编写:
-
将int转换为str:
"2 + 2 = " + str(2 + 2)
-
使用str.format方法:
"2+2={:d}".format(2 + 2)
英文:
In python, it's different type,and you could not use + operator on type str and int.
for your case you can write below:
1.cover int to str:
"2 + 2 = " + str( 2 + 2)
2.use str.format method
"2+2={:d}".format(2+2)
答案3
得分: 2
你需要将`2+2`转换为字符串,然后再将其连接到`"2+2"`之后。
```python
print("2 + 2 = "+str(2+2))
或者使用f-strings更好
print(f"2 + 2 = {2+2}")
如果你想避免重复求和,你可以使用devtools
库(需要通过pip
安装)
from devtools import debug
debug(f"{3+5=}")
>>> '3+5=8'
英文:
You have to convert 2+2
into a string before concatenating it to "2+2"
.
print("2 + 2 = "+str(2+2))
or even better, with f-strings
print(f"2 + 2 = {2+2}")
If you want to avoid repeating the sum, you can use the devtools
library (to be installed via pip
)
from devtools import debug
debug(f"{3+5=}")
>>> '3+5=8'
答案4
得分: 1
将一个字符串 "2 + 2 =" 添加到一个整数 (4) 中。首先将整数转换为字符串,然后将这两个字符串相加:
"2 + 2 = " + str(2 + 2)
英文:
You are trying to add a string "2 + 2 =" to an int (4). Turn the int into a string first and then add the two strings together:
"2 + 2 = " + str(2 + 2)
答案5
得分: 1
'+'操作符在Python中将两个相同类型的项目相加 - 两个字符串连接在一起变得更长,或者两个数字相加变成一个组合的单个数字。你正在将一个字符串'"2+2="'和一个数字(2+2)=4相加,这在逻辑上是没有意义的。
要么将两者都变成字符串
`print(""2 + 2 = "" + str(2 + 2))`
要么依赖print将数字转换为字符串进行输出,去掉'+'号,并加上逗号以显示你正在打印两个不同的东西。
`print(""2 + 2 = "", (2 + 2))`
英文:
The +
operand in python adds 2 items of the same type together - two strings join to become longer, or two numbers add to become a combined single number. Yuo are adding a string "2+2="
to a number (2+2)=4, which doesn't make logical sense.
Either make both strings
print ("2 + 2 = " + str( 2 + 2) )
or rely on print to transform the numbers into strings for output, remove the +
sign, and add a comma to show that you are printing two separate things.
print ("2 + 2 = ", ( 2 + 2) )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论