【问题标题】:Add spaces at the beginning of the print output in python在python中打印输出的开头添加空格
【发布时间】:2021-11-28 11:01:22
【问题描述】:

我想知道如何在 python 中使用 f-string 或格式在打印输出的开头添加 4 个空格?

这是我现在用来打印的:

print('{:<10}'.format('Constant'),'{:{width}.{prec}f}'.format(122, width=10, prec=3))

我的输出如下所示:

Constant     122.000

但我想要的是在输出中的常量之前有 4 个空格,例如:

( 4 spaces here )Constant     122.000

有什么想法吗?非常感谢!

【问题讨论】:

  • print(' {:&lt;10}'.format('Constant'), ... ?
  • 我不确定将使用哪种操作系统来运行我的代码。如果我只是在开头添加 4 个空格,Linux 和 Windows 是否会使用我的代码运行相同的结果? @Matthias
  • 就python打印而言,无论操作系统如何,我认为空格都应该是空格@AndrewSwainskeren

标签: python format f-string


【解决方案1】:

您可以使用' ' + string(按照建议),但更强大的方法可能是:

string="Test String leading space to be added"
spaces_to_add = 4
string_length=len(string) + spaces_to_add     # will be adding 4 extra spaces

string_revised=string.rjust(string_length)

结果:

'    Test String leading space to be added'

【讨论】:

    【解决方案2】:

    有几种方法可以做到:

    1. 如果Constant 真的是一个不变的常数,为什么不直接
      print(f"    {Constant}", ...)
      
      在你的其他字符串之前?
    2. 在您当前的实现中,您左对齐到 10 个字符的宽度。如果你把它换成右对齐,比如'{:&gt;12}'.format('Constant')(“常量”是8个字符,12 - 8 = 4个空格)它会在字符串前面放4个字符。

    这是我以前使用过的 Python f-string 语法备忘单:

    https://myshell.co.uk/blog/2018/11/python-f-string-formatting-cheatsheet/

    以及官方文档:PEP 3101

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2018-10-22
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      相关资源
      最近更新 更多