[英]How to parse the string into list of tuples
I have a string of the format -我有一个格式的字符串 -
" ( (4, 4), (11, 23), (8, 2), (12, 4), (7, 9) ) "
What is the best way in which I will get this string into meaningful integer tuples?将这个字符串转化为有意义的整数元组的最佳方法是什么? Lets say
fun(s)
is a function which takes such string
s
as parameter and returns list
of tuple
a
让我们说
fun(s)
是一个函数,它将string
s
作为参数并返回tuple
list
a
Ex.前任。
a = fun("( (2, 3), (1, 4) )")
print (a)
>>> [(2, 3), (1, 4)]
a[0]
>>> (2, 3)
a[0][1]
>>> 3
For this kind of thing, ast.literal_eval
is preferred to just the built-in eval
, especially if the string is something that may come from an unknown source.对于这种事情,
ast.literal_eval
比内置的eval
更ast.literal_eval
,特别是如果字符串可能来自未知来源。 The call interface is the same as eval
:调用接口与
eval
相同:
print(list(ast.literal_eval(s)))
However, ast.literal_eval
will guard against code insertions that may call system services (such as those that might delete files, etc.), and only accept literal values.但是,
ast.literal_eval
将防止可能调用系统服务(例如可能删除文件等)的代码插入,并且只接受文字值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.