如何为另一个字符串封装字符串?

How to unencapsulate string for another string?

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

例如,来自:

>>> string1
"u'abcde'"

我想得到:

>>> string2
'abcde'

您似乎需要函数 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'