简体   繁体   English

如何将字符串解析为元组列表

[英]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比内置的evalast.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将防止可能调用系统服务(例如可能删除文件等)的代码插入,并且只接受文字值。

You can use Python's built-in eval() function.您可以使用 Python 的内置eval()函数。

In this case, you can write your code like this:在这种情况下,您可以像这样编写代码:

s = " ( (4, 4), (11, 23), (8, 2), (12, 4), (7, 9) ) "
print(list(eval(s)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM