[英]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.