【问题标题】:How to unencapsulate string for another string?如何为另一个字符串封装字符串?
【发布时间】:2015-02-06 12:08:22
【问题描述】:

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

例如,来自:

>>> string1
"u'abcde'"

我想得到:

>>> string2
'abcde'

【问题讨论】:

  • string1.split("'")[1] 也可以。

标签: python string unicode


【解决方案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
  • @jamylak 我可以知道为什么吗?
  • 是的,详细地说,您可以在eval 中注入您想要的任何代码来删除您所有的文件和其他内容。
  • @AvinashRaj 因为eval 将评估任意(且具有潜在危险)代码,而ast.literal_eval 将仅评估Python 文字。请参阅the docs 和例如stackoverflow.com/q/1832940/3001761.
  • 谢谢^.*\b(jon|jamy)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
  • 2013-08-22
  • 1970-01-01
相关资源
最近更新 更多