【问题标题】:How to add commas and periods next to variables in print statement如何在打印语句中的变量旁边添加逗号和句点
【发布时间】:2021-12-04 03:20:24
【问题描述】:

我已经完成了我想要的代码,但是遇到了一个小语法问题。

我有一些打印语句可以打印我需要的内容,但它们的间距很奇怪,我希望它看起来像一个完整的句子,逗号和句点之间没有空格。

下面是几行:

     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, ".")

在这些行中,名称和年份是从输入中定义的,我只是对如何让它以正确的间距运行感到困惑。

感谢任何帮助!

非常感谢。

【问题讨论】:

    标签: python python-3.x printf python-3.5


    【解决方案1】:

    您确实应该像@Sandsten 上面所说的那样使用 f 字符串,但仅供您参考,下面是旧方法...

    print('{0}, you were born in {1}.').format(name, year)
    

    【讨论】:

      【解决方案2】:

      当您在print() 中用逗号分隔值时,它会添加空格。由于您使用的是 Python 3,因此您可以改用这样的 f 字符串

      print(f"{name}, you were born in {year}.")
      

      这里有很好的文档:https://docs.python.org/3/tutorial/inputoutput.html#

      【讨论】:

      • 乐于助人。如果您使用复选标记按钮接受我的回答,将不胜感激:)
      猜你喜欢
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      相关资源
      最近更新 更多