在python中将字符串转换为元组 [英] converting string to tuple in python

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

问题描述

我有一个从类似"('mono')"的软件返回的字符串,我需要将字符串转换为元组.

I have a string returnd from a software like "('mono')" from that I needed to convert string to tuple .

我在想使用ast.literal_eval("('mono')"),但是它说的是格式错误的字符串.

that I was thinking using ast.literal_eval("('mono')") but it is saying malformed string.

推荐答案

由于您需要元组,因此在某些情况下,您必须期望包含不止元素的列表.不幸的是,您没有给出琐碎的(mono)以外的示例,因此我们不得不猜测.这是我的猜测:

Since you want tuples, you must expect lists of more than element in some cases. Unfortunately you don't give examples beyond the trivial (mono), so we have to guess. Here's my guess:

"(mono)"
"(two,elements)"
"(even,more,elements)"

如果所有数据都是这样,请通过分割字符串(减去周围的括号)将其转换为列表,然后调用元组构造函数.即使在单元素情况下也可以使用:

If all your data looks like this, turn it into a list by splitting the string (minus the surrounding parens), then call the tuple constructor. Works even in the single-element case:

assert data[0] == "(" and data[-1] == ")"
elements = data[1:-1].split(",")
mytuple = tuple(elements)

或一步:elements = tuple(data[1:-1].split(",")). 如果您的数据与我的示例不同,看起来像我的示例,请编辑您的问题以提供更多详细信息.

Or in one step: elements = tuple(data[1:-1].split(",")). If your data doesn't look like my examples, edit your question to provide more details.

这篇关于在python中将字符串转换为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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