Reputation: 41
If I have a string always in the form 'a,b,c,d,e'
where the letters are positive or negative numbers, e.g '1,-2,3,4,-5'
and I want to turn it into the tuple e.g (1,-2,3,4,-5), how would I do this?
Upvotes: 4
Views: 1277
Reputation: 1125368
Split on ,
and map to int()
:
map(int, inputstring.split(','))
This produces a list; if you need a tuple, just wrap it in a tuple()
call:
tuple(map(int, inputstring.split(',')))
In Python 3, map()
returns a generator, so you would use a list comprehension to produce the list:
[int(el) for el in inputstring.split(',')]
Demo:
>>> inputstring = '1,-2,3,4,-5'
>>> map(int, inputstring.split(','))
[1, -2, 3, 4, -5]
>>> tuple(map(int, inputstring.split(',')))
(1, -2, 3, 4, -5)
Upvotes: 4
Reputation:
Another way:
>>> inputlist = '1,-2,3,4,-5'
>>> tuple(int(x) for x in inputlist.split(','))
(1, -2, 3, 4, -5)
>>>
Upvotes: 1
Reputation: 176990
One method would be to use ast.literal_eval
:
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and
None
.This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
>>> import ast
>>> ast.literal_eval('1,-2,3,4,-5')
(1, -2, 3, 4, -5)
Upvotes: 6