使用Python中对齐的新行打印字符串
有没有一种简单的方法可以打印一个字符串,其中包含一个新行使用Python中对齐的新行打印字符串,python,string,printing,format,newline,Python,String,Printing,Format,Newline,有没有一种简单的方法可以打印一个字符串,其中包含一个新行\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 = '[A]: ' B = 'this is\na s
\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 = '[A]: '
B = 'this is\na string\nwith a new line'
print('{:<10} {}'format(A, B))
[A]: this is
a string
with a new line
我可能可以拆分
B
,但我想知道是否有一种可选的方法可以做到这一点一个简单的方法是用新行替换新行和11(11是因为中的10{:用'\n'
替换'\n'
怎么样?(包括10个空格)。您应该将10个空格更改为9,因为“:”后面有空格A@latsha:嗯,不应该是11,我已经根据问题中最后一个片段计算了每行的空格数。无论如何,你可以测试一下
B2 = B.replace('\n','\n'+11*' ')
print('{:<10} {}'.format(A, B2))
$ 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