Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, is it possible to escape newline characters when printing a string?

I want the newline \n to show up explicitly when printing a string retrieved from elsewhere. So if the string is 'abc\ndef' I don't want this to happen:

>>> print(line) abc def 

but instead this:

>>> print(line) abc\ndef 

Is there a way to modify print, or modify the argument, or maybe another function entirely, to accomplish this?

like image 842
Tyler Avatar asked Mar 13 '13 17:03

Tyler


People also ask

How do you escape a newline character in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

How do you print a string with a line break in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

Does print in Python add a newline?

In Python, the built-in print function is used to print content to the standard output, which is usually the console. By default, the print function adds a newline character at the end of the printed content, so the next output by the program occurs on the next line.

How do you escape a new line in a string?

A commonly used escape sequence is \n, which inserts a newline character into a string.


2 Answers

Just encode it with the 'string_escape' codec.

>>> print "foo\nbar".encode('string_escape') foo\nbar 

In python3, 'string_escape' has become unicode_escape. Additionally, we need to be a little more careful about bytes/unicode so it involves a decoding after the encoding:

>>> print("foo\nbar".encode("unicode_escape").decode("utf-8")) 

unicode_escape reference

like image 178
mgilson Avatar answered Sep 17 '22 16:09

mgilson


Another way that you can stop python using escape characters is to use a raw string like this:

>>> print(r"abc\ndef") abc\ndef 

or

>>> string = "abc\ndef" >>> print (repr(string)) >>> 'abc\ndef' 

the only proplem with using repr() is that it puts your string in single quotes, it can be handy if you want to use a quote

like image 34
PurityLake Avatar answered Sep 20 '22 16:09

PurityLake