gpt4 book ai didi

python - 将字符串转换为正数和负数列表

转载 作者:太空狗 更新时间:2023-10-30 01:54:52 24 4
gpt4 key购买 nike

如果我有一个始终采用 'a,b,c,d,e' 形式的字符串,其中字母是正数或负数,例如 '1,-2,3 ,4,-5' 并且我想将它变成元组,例如 (1,-2,3,4,-5),我该怎么做?

最佳答案

一种方法是使用 ast.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('1,-2,3,4,-5')
(1, -2, 3, 4, -5)

关于python - 将字符串转换为正数和负数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18164598/

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