Reputation: 543
My goal is to convert a string into a tuple
Currently, I have a string that is surround by parentheses with its contents separated by commas.
>>>'1, 4, 1994' (variable name birthday)
(1, 4, 1994) # desired output
I have been trying to use split() to convert the string into tuple, but
tuple(birthday.split())
('1,', '4,', '1994')
but the contents are surrounded by subsequent parentheses.
What pythonic methods can I use to make the conversion?
Upvotes: 0
Views: 102
Reputation: 5666
You can use ast.literal_eval
>>> import ast
>>> s = '1, 4, 1994'
>>> ast.literal_eval(s)
>>> (1,4,1994)
Upvotes: 2
Reputation: 16081
You can do like this,
In [35]: tuple(map(int,birthday.split(',')))
Out[35]: (1, 4, 1994)
Problem with your spit function. Use ,
to split.
Upvotes: 4