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!
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.
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.
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 .
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.
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/'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With