简体   繁体   English

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

[英]Print string with new lines aligned in Python

Is there an easy way to print a string that contains a new line \\n , aligned to the left after a certain number of characters? 有没有一种简单的方法来打印包含换行\\n的字符串,该字符串在一定数目的字符后向左对齐?

Basically, what I have is something like 基本上,我所拥有的就像

A = '[A]: '
B = 'this is\na string\nwith a new line'

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

The problem is that with the new line, the next lines do not start at the 10th column: 问题在于,对于新行,下一行不会在第10列开始:

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

I would like something like 我想要类似的东西

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

I could maybe split B , but I was wondering if there was an optial way of doing this 我可能会拆分B ,但是我想知道是否存在一种可行的方法

An easy way to achieve this is replacing a new line with a new line and 11 (11 because of the 10 in {:<10} but you add an additional space in your format) spaces: 实现此目的的一种简单方法是用新行和11替换新行(由于{:<10}中为10,所以添加11,但是您在格式中添加了额外的空间):

B2 = B.replace('\n','\n           ')
print('{:<10} {}'.format(A, B2))

Or perhaps more elegantly: 或更优雅:

B2 = B.replace('\n','\n'+11*' ')
print('{:<10} {}'.format(A, B2))

Running this in python3 : 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM