从字符串解析元组? [英] Parse a tuple from a string?

查看:43
本文介绍了从字符串解析元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个与元组形式相同的字符串,例如,"(1,2,3,4,5)".将其转换为实际元组的最简单方法是什么?我想做的一个例子是:

tup_string = "(1,2,3,4,5)"tup = make_tuple(tup_string)

只是在字符串上运行 tuple() 使整个事物成为一个大元组,而我想做的是将字符串理解为一个元组.我知道我可以为此使用正则表达式,但我希望有一种成本更低的方法.想法?

解决方案

It 已经存在

<预><代码>>>>从 ast 导入literal_eval 作为make_tuple>>>make_tuple("(1,2,3,4,5)")(1, 2, 3, 4, 5)

但请注意极端情况:

<预><代码>>>>make_tuple("(1)")1>>>make_tuple("(1,)")(1,)

如果您的输入格式在这里与 Python 不同,您需要单独处理这种情况或使用另一种方法,例如 tuple(int(x) for x in tup_string[1:-1].split(',')).

Say I have a string that's of the same form a tuple should be, for example, "(1,2,3,4,5)". What's the easiest way to convert that into an actual tuple? An example of what I want to do is:

tup_string = "(1,2,3,4,5)"
tup = make_tuple(tup_string)

Just running tuple() on the string make the whole thing one big tuple, whereas what I'd like to do is comprehend the string as a tuple. I know I can use a regex for this, but I was hoping there's a less costly way. Ideas?

解决方案

It already exists!

>>> from ast import literal_eval as make_tuple
>>> make_tuple("(1,2,3,4,5)")
(1, 2, 3, 4, 5)

Be aware of the corner-case, though:

>>> make_tuple("(1)")
1
>>> make_tuple("(1,)")
(1,)

If your input format works different than Python here, you need to handle that case separately or use another method like tuple(int(x) for x in tup_string[1:-1].split(',')).

这篇关于从字符串解析元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆