gpt4 book ai didi

python - 在具有多个拆分器的python中拆分字符串

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:09 25 4
gpt4 key购买 nike

如何将如下所示的字符串变量拆分为各个组? var.split(",") 也拆分括号内的那些。

var = "(5, 'kghjsg'), (6, 'kghjsghk'), (7, 'jksgjsg'), (8, 'ksgshgk'), (9, 'hjsdhg')"

期望的结果:

[(5, 'kghjsg'),  
(6, 'kghjsghk'),
..
]

最佳答案

使用ast.literal_eval :

>>> from ast import literal_eval
>>> var = "(5, 'kghjsg'), (6, 'kghjsghk'), (7, 'jksgjsg'), (8, 'ksgshgk'), (9, 'hjsdhg')"
>>> literal_eval(var)
((5, 'kghjsg'), (6, 'kghjsghk'), (7, 'jksgjsg'), (8, 'ksgshgk'), (9, 'hjsdhg'))

来自文档:

Safely evaluate an expression node or a Unicode or Latin-1 encoded 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.

关于python - 在具有多个拆分器的python中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21124237/

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