Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert tuple in string to tuple object?

Tags:

python

tuples

In Python 2.7, I have the following string:

"((1, u'Central Plant 1', u'http://egauge.com/'),
(2, u'Central Plant 2', u'http://egauge2.com/'))"

How can I convert this string back to tuples? I've tried to use split a few times but it's very messy and makes a list instead.

Desired output:

((1, 'Central Plant 1', 'http://egauge.com/'),
(2, 'Central Plant 2', 'http://egauge2.com/'))

Thanks for the help in advance!

like image 602
hao_maike Avatar asked May 14 '13 00:05

hao_maike


People also ask

How do you convert a string to a tuple?

Method #1 : Using map() + int + split() + tuple() This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple.

How do you convert a tuple to a tuple?

Tuple String to a Tuple Using The eval() Function in Python The eval() function is used to evaluate expressions. It takes a string as an input argument, traverses the string, and returns the output. We can directly convert the tuple string to a tuple using the eval() function as shown below.

How do you convert a tuple to an object in Python?

Method 1: To convert a Python set to a tuple, use the tuple(my_set) function. Method 2: To convert a Python tuple to a set, use the set(my_tuple) function. Method 3: To convert a Python tuple of mutable elements to a set, use the expression set(tuple(x) for x in my_tuple) to avoid a TypeError .

Which of the following is used to convert string into tuple?

Python's built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas.


1 Answers

You should use the literal_eval method from the ast module which you can read more about here.

>>> import ast
>>> s = "((1, u'Central Plant 1', u'http://egauge.com/'),(2, u'Central Plant 2', u'http://egauge2.com/'))"
>>> ast.literal_eval(s)
((1, u'Central Plant 1', u'http://egauge.com/'), (2, u'Central Plant 2', u'http://egauge2.com/'))
like image 174
HennyH Avatar answered Sep 18 '22 20:09

HennyH