Is there an easy way to convert a string containing a string literal into the string it represents?

前端 未结 2 821
隐瞒了意图╮
隐瞒了意图╮ 2021-01-23 02:01

I\'m trying to (slightly) improve a script that does a quick-and-hacky parse of some config files.

Upon recognising \"an item\" read from the file, I need to try to conv

相关标签:
2条回答
  • 2021-01-23 02:48

    ast.literal_eval() handles all simple Python literals, and most compound literals.

    0 讨论(0)
  • 2021-01-23 02:53

    ... And sure enough, I just found the answer after I posted.

    Even better than what I was looking for is ast.literal_eval: ast — Abstract Syntax Trees

    It can evaluate any Python expression consisting solely of literals, which makes it safe. It also means I can recognise items from the config file that are potentially numbers or strings without having attempt multiple conversions, falling back to the next conversion on a ValueError exception. I don't even have to figure out what type the item is.

    It's even way more flexible than I need, which could be a problem if I cared about making sure the item was only a number or a string, but I don't:

    >>> ast.literal_eval('{"foo": [23.8, 170, (1, 2, 3)]}')
    {'foo': [23.8, 170, (1, 2, 3)]}
    
    0 讨论(0)
提交回复
热议问题