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 ‘abcndef’ I don’t want this to happen:

>>> print(line)
abc
def

but instead this:

>>> print(line)
abcndef

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Just encode it with the 'string_escape' codec.

>>> print "foonbar".encode('string_escape')
foonbar

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("foonbar".encode("unicode_escape").decode("utf-8"))

unicode_escape reference

Method 2

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

>>> print(r"abcndef")
abcndef

or

>>> string = "abcndef"
>>> print (repr(string))
>>> 'abcndef'

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

Method 3

Simplest method:
str_object.replace("n", "\n")

The other methods are better if you want to show all escape characters, but if all you care about is newlines, just use a direct replace.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x