在 Python 中使用对齐的新行打印字符串

Per*_*oob 4 python printing string format newline

有没有一种简单的方法来打印包含新行的字符串,\n在一定数量的字符后向左对齐?

基本上,我所拥有的是

A = '[A]: '
B = 'this is\na string\nwith a new line'

print('{:<10} {}'format(A, B))
Run Code Online (Sandbox Code Playgroud)

问题是对于新行,下一行不会从第 10 列开始:

[A]:       this is
a string
with a new line
Run Code Online (Sandbox Code Playgroud)

我想要类似的东西

[A]:       this is
           a string
           with a new line
Run Code Online (Sandbox Code Playgroud)

我可能会分裂B,但我想知道是否有一种最佳的方式来做到这一点

Wil*_*sem 5

实现此目的的一种简单方法是用新行和 11(11 个,因为 10 英寸,{:<10}但您在格式中添加了额外的空间)替换新行:

B2 = B.replace('\n','\n           ')
print('{:<10} {}'.format(A, B2))
Run Code Online (Sandbox Code Playgroud)

或者也许更优雅:

B2 = B.replace('\n','\n'+11*' ')
print('{:<10} {}'.format(A, B2))
Run Code Online (Sandbox Code Playgroud)

运行这个python3

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> A = '[A]: '
>>> B = 'this is\na string\nwith a new line'
>>> B2 = B.replace('\n','\n           ')
>>> print('{:<10} {}'.format(A, B2))
[A]:       this is
           a string
           with a new line
Run Code Online (Sandbox Code Playgroud)