我想在python中打印同一行字符串后面的数字和。
print("Your answer is correct, this is your score:" + score=score+1)
在打印前给加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
>>>
您可以使用f-string,但您也应该在打印之前设置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)