TAGS :Viewed: 3 - Published at: a few seconds ago

[ how to print '\n' and not '\\n' ]

I am making a application where I am using some auto generate regular expressions which are multi line is the reg Ex string contains \n.

Now every time i execute a generate command i would like to print the command to console also for documentation ect.

INFO: Command execute: (regular expression)

however if i just print my Reg Ex string containing the \n I also get newline in the printout which is not desirable.

INFO: Command execute: (regular expre

I can get it to print the newline \n by adding an escape char making it \\n and it is also how it looks on the print out.

INFO: Command execute: (regular expre\\nssion)

This is not desirable either. What I am looking for is to be able to print it like following.

INFO: Command execute: (regular expre\nssion)

Is this possible ?


Answer 1

Use the built-in function repr() to get the string that would reproduce that object when evaluated:

>>> text = 'INFO: Command execute: (regular expre\nssion)'
>>> print(text)
INFO: Command execute: (regular expre
>>> print(repr(text))
'INFO: Command execute: (regular expre\nssion)'

Answer 2

You can try this. String prefix r makes it ignore all escapes.

a = r"Hello\nworld"
print a # Hello\nworld

If you still need new lines while using r, you can use triple quote sintax

b = r"""Big \n long
print b
# Big \n long
# \n
# string