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

4
有没有一种简单的方法来打印一个包含换行符 \n 的字符串,并在一定数量的字符后左对齐?
基本上,我有类似下面的东西:
A = '[A]: '
B = 'this is\na string\nwith a new line'

print('{:<10} {}'format(A, B))

问题在于新行的下一行不会从第十列开始:
[A]:       this is
a string
with a new line

我希望你能为我提供一些类似的内容

[A]:       this is
           a string
           with a new line

我可以把B分开,但我想知道是否有更好的方法。


1
'\n' 替换为 '\n ' 怎么样?(包括10个空格) - Willem Van Onsem
1个回答

5
一个简单的方法是用一个新行和11个空格(因为在格式中有10个{:<10},但你需要添加额外的空格)来替换一个新行:
B2 = B.replace('\n','\n           ')
print('{:<10} {}'.format(A, B2))

也许更优美的方式是:
B2 = B.replace('\n','\n'+11*' ')
print('{:<10} {}'.format(A, B2))

在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

你应该将10个空格改为9个,因为A后面有一个空格。 - latsha
@latsha:嗯,应该是11吧,我根据问题中的最后一个片段计算了每行的空格数。 - Willem Van Onsem
无论如何,您都可以测试它。 - latsha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接