打印新行对齐 Python 的字符串
Print string with new lines aligned in Python
有没有简单的方法来打印包含新行 \n
、在一定数量的字符后向左对齐的字符串?
基本上,我有的是
A = '[A]: '
B = 'this is\na string\nwith a new line'
print('{:<10} {}'format(A, B))
问题是新行的下一行不是从第 10 列开始的:
[A]: this is
a string
with a new line
我想要类似的东西
[A]: this is
a string
with a new line
我也许可以拆分 B
,但我想知道是否有这样做的可选方法
实现此目的的一种简单方法是用新行和 11 替换新行(11 是因为 {:<10}
中的 10,但您在格式中添加了额外的 space)spaces:
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
有没有简单的方法来打印包含新行 \n
、在一定数量的字符后向左对齐的字符串?
基本上,我有的是
A = '[A]: '
B = 'this is\na string\nwith a new line'
print('{:<10} {}'format(A, B))
问题是新行的下一行不是从第 10 列开始的:
[A]: this is
a string
with a new line
我想要类似的东西
[A]: this is
a string
with a new line
我也许可以拆分 B
,但我想知道是否有这样做的可选方法
实现此目的的一种简单方法是用新行和 11 替换新行(11 是因为 {:<10}
中的 10,但您在格式中添加了额外的 space)spaces:
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