Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string literals to strings?

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.

like image 798
Dave Halter Avatar asked May 08 '12 07:05

Dave Halter


People also ask

How do you convert a string to a string literal in Python?

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.

Can you change string literals?

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.

Is string and string literal same?

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.

How do you escape a string literal?

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 \' .


1 Answers

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()).

like image 168
Tim Pietzcker Avatar answered Sep 23 '22 23:09

Tim Pietzcker