【发布时间】:2015-02-06 12:08:22
【问题描述】:
我想从另一个字符串中解封装一个字符串(在 Python 中)。
例如,来自:
>>> string1
"u'abcde'"
我想得到:
>>> string2
'abcde'
【问题讨论】:
-
string1.split("'")[1]也可以。
我想从另一个字符串中解封装一个字符串(在 Python 中)。
例如,来自:
>>> string1
"u'abcde'"
我想得到:
>>> string2
'abcde'
【问题讨论】:
string1.split("'")[1] 也可以。
好像你想要函数eval
>>> stri = "u'abcde'"
>>> eval(stri)
'abcde'
>>> help(eval)
Help on built-in function eval in module builtins:
eval(...)
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
根据下面的 cmets,您需要使用 ast.literal_eval 函数而不是内置 eval 函数,因为 eval 将评估任意(且具有潜在危险)代码,而 ast.literal_eval 只会评估 Python 文字。
>>> import ast
>>> stri = "u'abcde'"
>>> ast.literal_eval(stri)
'abcde'
【讨论】:
ast.literal_eval 而不是eval
eval 中注入您想要的任何代码来删除您所有的文件和其他内容。
eval 将评估任意(且具有潜在危险)代码,而ast.literal_eval 将仅评估Python 文字。请参阅the docs 和例如stackoverflow.com/q/1832940/3001761.
^.*\b(jon|jamy)