Weiner Nir
Weiner Nir

Reputation: 1475

Python, Print to file without functionality of "\n"

I am trying to print string to file, but I want it this way:

string = "asdfasdf \n awefawe"

I want it to be printed as it is. so the file contains:

asdfasdf \n awefawe

AND NOT

asdfasdf
 awefawe

How do I do that? I tried:

f1=open('./testfile.txt', 'w+')
f1.write(body)

Edit: I don't want to change the string I just want to print it as it is. Even to stdout. I don't care where. I want to know what the string contains. It is not only about \n

Upvotes: 1

Views: 113

Answers (4)

zwol
zwol

Reputation: 140455

If you can't modify the code that sets the value of string (as suggested by the other answers), you can use one of the Python-specific codecs that convert "special" characters to the equivalent Python-string-literal escape sequence:

>>> print "abc\ndef".encode("string_escape")
abc\ndef

If the string may contain non-ASCII characters you may want unicode_escape instead, depending on your larger requirements:

>>> print "Ā".encode("string_escape")
\xc4\x80
>>> print u"Ā".encode("unicode_escape")
\u0100

Technically string_escape can only be applied to byte strings, and unicode_escape to Unicode strings, but Python 2 lets you get away with using either as long as all the characters fall in the ASCII range (i.e. U+0000 through U+007F). I'm not sure what the Python 3 equivalents are -- the .encode method seems to not exist on bytes objects in 3.2...

Upvotes: 4

caleb531
caleb531

Reputation: 4361

Python interprets \n within strings as a newline character. Therefore, to print a literal backslash, simply escape the backslash using another backslash, like so:

string = "asdfasdf \\n awefawe"

Upvotes: 1

jwodder
jwodder

Reputation: 57460

Modify the definition of string so that it ends up containing \n rather than a newline. This can be done with either:

string = r"asdfasdf \n awefawe"

or:

string = "asdfasdf \\n awefawe"

Upvotes: 4

Matt Williamson
Matt Williamson

Reputation: 40193

You have to escape the backslash.

string = "asdfasdf \\n awefawe"

Upvotes: 0

Related Questions