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

Python 如何为另一个字符串取消封装字符串?,python,string,unicode,Python,String,Unicode,我想从另一个字符串中取消封装一个字符串(在Python中) 例如,来自: >>> string1 "u'abcde'" 我想得到: >>> string2 'abcde' 似乎您需要函数eval >>> stri = "u'abcde'" >>> eval(stri) 'abcde' >>> help(eval) Help on built-in function eval in module bui

我想从另一个字符串中取消封装一个字符串(在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\u eval
函数而不是内置的eval函数,因为eval将评估任意(和潜在危险)代码,而
ast.literal\u eval
将只评估Python文本

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

为了安全起见,你应该使用
ast.literal_eval
而不是
eval
@jamylak我可以知道为什么吗?是的,详细地说,你可以在
eval
中插入任何你想要的代码来删除你的所有文件和其他东西。@AvinashRaj因为
eval
会计算任意(和潜在的危险)代码,而
ast.literal\u eval
将只计算Python文本。请参阅,例如.“谢谢”
^..*\b(jon | jamy)
string1.split(“”)[1]
也有效。