如何在打印语句中的变量旁边添加逗号和句点
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)
我已经完成了我想要的代码,但遇到了一个小语法问题。
我有一些打印语句可以打印我需要的内容,但它们的间距很奇怪,我希望它看起来像一个完整的句子,逗号和句号之间没有空格。
这是几行:
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)