[英]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替换新行(由于{:<10}
中为10,所以添加11,但是您在格式中添加了额外的空间):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.