简体   繁体   English

Python将字符串文字转换为字符串

[英]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.

相关问题 如何在 python 3 中将字节文字列表转换为字符串文字? - How do I convert a list of byte literals into string literals in python 3? 在Python中将UTF-8转换为字符串文字 - Convert UTF-8 to string literals in Python Python - 如何将转义序列转换为字符串文字 - Python - How to convert escaped sequence to string literals 如何将一列字符串转换为 python 文字并提取值 - How to convert a column of strings to python literals and extract the values 在Python中使用正则表达式匹配C ++字符串和字符串文字 - Match C++ Strings and String Literals using regex in Python 所有 JSON 字符串在语法上是否也有效 Python 字符串文字? - Are all JSON strings also syntactically valid Python string literals? 编写文件时从Python字符串中删除字符串文字 - Remove String Literals from Python Strings when writing a File 如何在Python 2.7中将unicode字符串转换为字符串文字? - How can I convert a unicode string into string literals in Python 2.7? 如何使用python 3将Unicode文字的字符串表示形式从文件转换为真正的Unicode文字? - How to convert a string representation of unicode literals from a file, into real unicode literals using python 3? 将字符串转换为python中的字符串列表 - Convert string to list of strings in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM