lznt
lznt

Reputation: 2576

python 3 - how to keep "\" from command line argument as raw string

Code is very simple:

import sys
for arg in sys.argv:
    print(arg)

When I run it using:

myProgram.py \\

It prints:

C:\myProgram.py
\\

Since "\" is special, under the hood, python addes extra "\"s so the inputed "\\" becomes "\\\\", and when it prints it becames to "\\" again. How can I stop this, or delete the extra "\"s added by python? So when the inputed argument is "\\", it prints "\"; and when the inputed argument is "\t", it prints a [tab]; "\n" to print a new line; etc?

My search leads me to try the "raw string", so I changed my code to

import sys
for arg in sys.argv:
    arg.replace(r'\\',r'\')
    print(arg)

But it throws error saying

SyntaxError: EOL while scanning string literal

Seems the "raw string" is not working here?

UPDATE: Screenshot with slight change

program

output

Upvotes: 3

Views: 6036

Answers (2)

Rudy Bunel
Rudy Bunel

Reputation: 794

I think that this problem is explained in this FAQ

Upvotes: 1

alexanderlukanin13
alexanderlukanin13

Reputation: 4715

You want to evaluate argument as string, so you can use eval

import sys
for arg in sys.argv:
    print(eval('"' + arg.replace('"', '\\"') + '"'))

WARNING: you should not use this approach in production, because Eval really is dangerous

Upvotes: 2

Related Questions