Python convert string literals to strings

Dave Halter picture Dave Halter · May 8, 2012 · Viewed 7.2k times · Source

I want to convert a string literal like r"r'\nasdf'" to a string ('\\nasdf' in this case).

Another case: r"'\nasdf'" to '\nasdf'. I hope you get it.

This is important, because I have a parser of python scripts, that wants to know the exact contents of a string literal.

Is eval a clever solution? The string literals are filtered before (with tokenize) and should not cause security liabilities. Aren't there any nobler solutions than evaluating a literal? A parser library maybe?

Edit: Added other examples, to avoid misunderstandings.

Answer

Tim Pietzcker picture Tim Pietzcker · May 8, 2012

You want the ast module:

>>> import ast
>>> raw = r"r'\nasdf'"
>>> ast.literal_eval(raw)
'\\nasdf'
>>> raw = r"'\nasdf'"
>>> ast.literal_eval(raw)
'\nasdf'

This is a safe method for evaluating/parsing strings that contain Python source code (unlike eval()).