[英]How to add commas and periods next to variables in print statement
我已經完成了我想要的代碼,但是遇到了一個小的語法問題。
我有一些打印語句可以打印我需要的內容,但是它們的間距很奇怪,我希望它看起來像一個完整的句子,逗號和句點之間沒有空格。
以下是幾行:
if year < 2001:
print(name, ",", "you were born in", year,".")
elif year > 2100:
print(name, ",", "you were born in", year,".")
else:
print(name, ",", "you were born in", year,", which is the 21st century.")
print(name, "'s classification is", classification, ".")
在這些行中,名稱和年份是根據輸入定義的,我只是對如何讓它以正確的間距運行感到困惑。
任何幫助表示贊賞!
非常感謝。
當您在print()
中用逗號分隔值時,它會添加空格。 由於您使用的是 Python 3,因此您可以使用這樣的 f-strings
print(f"{name}, you were born in {year}.")
這里有很棒的文檔: https : //docs.python.org/3/tutorial/inputoutput.html#
您確實應該像@Sandsten 上面所說的那樣使用 f 字符串,但是對於您的信息,有如下舊方法...
print('{0}, you were born in {1}.').format(name, year)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.