tags:

views:

1663

answers:

5

How to get rid of '\n' at the end of a line ?

+20  A: 
"string \n".strip();

or

"string \n".rstrip();
Ionuț G. Stan
+18  A: 

If, as Rolf suggests in his comment, you want to print text without having a newline automatically appended, use

print "foo",

Note the trailing comma.

unwind
Yeah, that may be the problem.
Ionuț G. Stan
+2  A: 

If you want a slightly more complex and explicit way of writing output:

import sys
sys.stdout.write("string")

Then you would responsible for your own newlines.

Gregg Lind
+6  A: 

Get rid of just the "\n" at the end of the line:

>>> "string \n".rstrip("\n")
'string '

Get rid of all whitespace at the end of the line:

>>> "string \n".rstrip()
'string'

Split text by lines, stripping trailing newlines:

>>> "line 1\nline 2 \nline 3\n".splitlines()
['line 1', 'line 2 ', 'line 3']
Ryan Ginstrom
+4  A: 

In Python 3, to print a string without a newline, set the end to an empty string:

print("some string", end="")