Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `\n` not working in Python

Tags:

bash

shell

cmd

I'm trying following example :

python -c "import sys; print sys.argv[1]" "test\ntest"

Output :

test\ntest

But I want following

test 
test

Update 1# As @devnull suggested can solve the problem if user itself pass the with $ but how about python should take care of this ?

I've tried :

python -c "import sys; print '$' + sys.argv[1]" 'test\ntest'

but output :

$test\ntest
like image 244
Rahul Patil Avatar asked Jan 03 '14 11:01

Rahul Patil


People also ask

Why does n not work in Python?

This occurs because, according to the Python Documentation: The default value of the end parameter of the built-in print function is \n , so a new line character is appended to the string. 💡 Tip: Append means "add to the end".

What does '\ n do in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

What does R '\ n means in Python?

"\r\n" is the default Windows style for line separator. "\r" is classic Mac style for line separator.

Can you put \n in a string?

Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.


2 Answers

As deed02392 mentioned, shell sends the characters literally, so python "escapes" the backslash internally. To see what I mean, try

python -c "import sys; print repr(sys.argv[1])" "test\ntest"
'test\\ntest'

To work around this, do:

python -c "import sys; print sys.argv[1].decode('string_escape')" "test\ntest"
test
test
like image 163
skoll Avatar answered Oct 14 '22 18:10

skoll


Tell the shell to pass what you want to see:

python -c "import sys; print sys.argv[1]" $'test\ntest'

This would produce:

test
test

The $'string' syntax is referred to as ANSI-C Quoting.


Another way would be to tell the shell to interpret your original output:

python -c "import sys; print sys.argv[1]" 'test\ntest' | xargs -0 echo -en

This would also produce:

test
test
like image 25
devnull Avatar answered Oct 14 '22 18:10

devnull