[英]Python convert string literals to strings
I want to convert a string literal like r"r'\\nasdf'"
to a string ( '\\\\nasdf'
in this case). 我想将字符串文字如
r"r'\\nasdf'"
转换为字符串(在本例中为'\\\\nasdf'
)。
Another case: r"'\\nasdf'"
to '\\nasdf'
. 另一个案例:
r"'\\nasdf'"
到'\\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. 这很重要,因为我有一个python脚本解析器,想要知道字符串文字的确切内容。
Is eval
a clever solution? eval
是一个聪明的解决方案吗? The string literals are filtered before (with tokenize
) and should not cause security liabilities. 字符串文字在之前被过滤(使用
tokenize
),不应该导致安全责任。 Aren't there any nobler solutions than evaluating a literal? 除了评估文字之外,还没有更高级的解决方案吗? A parser library maybe?
解析器库可能吗?
Edit : Added other examples, to avoid misunderstandings. 编辑 :添加其他示例,以避免误解。
You want the ast
module : 你想要
ast
模块 :
>>> 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()
). 这是一种评估/解析包含Python源代码的字符串的安全方法(与
eval()
不同)。
Yes, there are: 是的,有:
>>> s = r'\nasdf'
>>> s.decode('string-escape')
'\nasdf'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.