gpt4 book ai didi

列出最佳实践的 Python 字符串

转载 作者:太空狗 更新时间:2023-10-30 00:36:26 24 4
gpt4 key购买 nike

我有一个像这样的字符串 ['first', 'sec', 'third']"

将其转换为字符串列表的最佳方法是什么,即。 ['第一', '第二', '第三']

最佳答案

我会使用 literal_eval() , 这是安全的:

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

>>> import ast
>>> ast.literal_eval("['first', 'sec', 'third']")
['first', 'sec', 'third']

除了文字表达式,它不计算任何东西:

>>> ast.literal_eval('"hello".upper()')
...
ValueError: malformed string

>>> ast.literal_eval('"hello"+" world"')
...
ValueError: malformed string

关于列出最佳实践的 Python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18077309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com