简体   繁体   中英

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?

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:

[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

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:

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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