Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a string into list of positive and negative numbers

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?

like image 324
robbie james Avatar asked Dec 21 '22 01:12

robbie james


2 Answers

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)
like image 107
agf Avatar answered Mar 01 '23 23:03

agf


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)
like image 30
Martijn Pieters Avatar answered Mar 02 '23 01:03

Martijn Pieters