Python convert string literals to strings

爷,独闯天下 提交于 2019-12-06 17:19:53

问题


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.


回答1:


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




回答2:


Yes, there are:

>>> s = r'\nasdf'
>>> s.decode('string-escape')
'\nasdf'


来源:https://stackoverflow.com/questions/10494789/python-convert-string-literals-to-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!