4

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

1
  • 1
    What about replacing the '\n' with '\n '? (including 10 spaces). Commented Jan 16, 2017 at 10:00

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

you should change 10 spaces to 9 because of space after ":" in A
@latsha: euh shouldn't it be 11, I've counted the number of spaces per new line based on the last fragment in the question.
anyway you can test it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.