[英]How do I print a sum of numbers after a string in python?
我想在python的同一行中的字符串之后打印数字的总和。
print("Your answer is correct, this is your score:" + score=score+1)
您可以使用 f 字符串,但您还应该在打印之前设置score
的值,以便更清楚发生了什么:
score += 1
print(f"Your answer is correct, this is your score: {score}")
您可以按照自己的方式进行操作,但必须先将score
转换为字符串,然后才能将其(通过+
)连接到另一个字符串:
score += 1
print("Your answer is correct, this is your score: " + str(score))
另一种方法是将score
作为参数添加到print
; 在这种情况下,您不必将其转换为字符串:
score += 1
print("Your answer is correct, this is your score: ", score)
打印前将分数加 1。
您还需要将分数转换为字符串,然后才能连接它。 或者您可以使用字符串格式,这更简单。
score += 1
print(f"Your answer is correct, this is your score: {score}"
如果使用 f 字符串,则可以在格式中添加操作:
print(f"Your answer is correct, this is your score: {score+1}")
有几种方法
>>> score = 10 #you do your calculation first
>>> print("Your answer is correct, this is your score:", score)#print can take any number of arguments
Your answer is correct, this is your score: 10
>>> print("Your answer is correct, this is your score: " + str(score))#make it a string first and concatenate it
Your answer is correct, this is your score: 10
>>> print(f"Your answer is correct, this is your score: {score}")#use f-string
Your answer is correct, this is your score: 10
>>>
也有 2 或 3 种其他方法来制作字符串,但我推荐第一个和第三个示例,特别是 f-string,它们很棒。
此外,在 python 3.8 中,他们引入了赋值表达式:=
,因此您也可以像最初尝试的那样进行操作,只需进行一些调整...
>>> score=10
>>> print("Your answer is correct, this is your score:", (score:=score+1))
Your answer is correct, this is your score: 11
>>> score
11
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.