V Anon
V Anon

Reputation: 543

converting string into a tuple

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

Answers (3)

Sohaib Farooqi
Sohaib Farooqi

Reputation: 5666

You can use ast.literal_eval

>>> import ast
>>> s = '1, 4, 1994'
>>> ast.literal_eval(s)
>>> (1,4,1994)

Upvotes: 2

Rahul K P
Rahul K P

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

jpp
jpp

Reputation: 164693

You need to convert str to int and specify a sep argument for str.split:

res = tuple(map(int, '1, 4, 1994'.split(', ')))  # (1, 4, 1994)

Upvotes: 2

Related Questions