【问题标题】:How to print a little space after a every new line in python [duplicate]如何在python中的每一行之后打印一个小空格[重复]
【发布时间】:2020-01-09 11:28:06
【问题描述】:

我正在尝试打印一个字符串。

目前打印如下:print("\t" + errorstr)

       HTTPConnectionPool(host='localhost', port=10248): Max retries exceeded with url: /healthz 

(Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f9a92d5e6d0>: 

Failed to establish a new connection: [Errno 111] Connection refused',))

仅在第一行添加选项卡。

然后我尝试了:

print("\t"+u"{: ^32s}".format(errorstr))

但它仍然提供相同的输出。

我希望它是这样的:

     HTTPConnectionPool(host='localhost', port=10248): Max retries exceeded with url: /healthz 

     (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 
     0x7f9a92d5e6d0>: 

     Failed to establish a new connection: [Errno 111] Connection refused',))

每一行都应包含tab 空格。我如何在python 中做到这一点?

PS:我使用 python 2.7 是有原因的,所以我无法更改版本,我想使用默认的 python 包来执行此操作,而不是任何第三方库

【问题讨论】:

标签: python


【解决方案1】:

我会尝试进行字符串替换以在每个新行前面注入一个制表符:print("\t" + errorstr.replace("\n", "\n\t"))

【讨论】:

    【解决方案2】:

    您的错误字符串errorstr 中有多个换行符\n,您需要将每个换行符替换为换行符和制表符\t,如下所示:

    print("\t" + errorstr.replace("\n", "\n\t"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2020-04-13
      • 2020-10-31
      • 2021-06-30
      • 2017-10-12
      • 1970-01-01
      相关资源
      最近更新 更多