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.
In Python, when you prefix a string with the letter r or R such as r'...' and R'...' , that string becomes a raw string. Unlike a regular string, a raw string treats the backslashes ( \ ) as literal characters.
The behavior is undefined if a program attempts to modify any portion of a string literal. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory.
The main difference between String Literal and String Object is that String Literal is a String created using double quotes while String Object is a String created using the new() operator. String is a set of characters. Generally, it is necessary to perform String operations in most applications.
String literal syntaxUse the escape sequence \n to represent a new-line character as part of the string. Use the escape sequence \\ to represent a backslash character as part of the string. You can represent a single quotation mark symbol either by itself or with the escape sequence \' .
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With