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?
When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
Create an empty string and using a for loop iterate through the elements of the tuple and keep on adding each element to the empty string. In this way, the tuple is converted to a string. It is one of the simplest and the easiest approaches to convert a tuple to a string in Python.
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. Any non-sequence object as argument results in TypeError.
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(','))
.
I would recommend using literal_eval
.
If you are not comfortable with literal_eval
or want to have more control on what gets converted you can also disassemble the string, convert the values and recreate the tuple.
Sounds more complicated than it is, really, it's a one-liner:
eg = '(102,117,108)' eg_tuple = map(int, eg.replace('(','').replace(')','').split(',')))
This would throw a ValueError
if any element (string) in the tuple is not convertible to int
, like, for example the '1.2'
in the string: '(1.2, 3, 4)'
.
The same can be achieved with regex:
import re eg = '(102,117,108)' et_tuple = tuple(map(int, re.findall(r'[0-9]+', eg)))
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