如何取消封装另一个字符串的字符串?

时间:2015-02-06 12:08:23

标签: python string unicode

我想从另一个字符串中取消封装字符串(在Python中)。

例如,来自:

>>> string1
"u'abcde'"

我想得到:

>>> string2
'abcde'

1 个答案:

答案 0 :(得分: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.

根据以下注释,您需要使用ast.literal_eval函数而不是内置eval函数,因为eval将评估任意(和潜在危险)代码,而ast.literal_eval将仅评估Python文字。

>>> import ast
>>> stri = "u'abcde'"
>>> ast.literal_eval(stri)
'abcde'