我想在python的同一行中的字串之后列印數字的總和。
print("Your answer is correct, this is your score:" score=score 1)
uj5u.com熱心網友回復:
列印前將分數加 1 。
您還需要將分數轉換為字串,然后才能連接它。或者您可以使用字串格式,這更簡單。
score = 1
print(f"Your answer is correct, this is your score: {score}"
uj5u.com熱心網友回復:
如果使用 f 字串,則可以在格式中添加操作:
print(f"Your answer is correct, this is your score: {score 1}")
uj5u.com熱心網友回復:
有幾種方法
>>> 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
>>>
uj5u.com熱心網友回復:
您可以使用 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/334525.html
