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?
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)
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)
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