Turn a string into a list of positive and negative numbers

If I have a string always in the form of 'a,b,c,d,e' , where the letters are positive or negative numbers, for example '1,-2,3,4,-5' , and I want to turn it into a tuple e.g. (1, -2,3,4, -5), how would I do this?

+4
source share
3 answers

One method is to use ast.literal_eval :

It is safe to evaluate a node expression or a string containing a Python expression. A string or node can contain only the following literary Python structures: strings, numbers, tuples, lists, dicts, booleans, and None .

This can be used to safely evaluate strings containing Python expressions from untrusted sources without having to analyze the values ​​themselves.

 >>> import ast >>> ast.literal_eval('1,-2,3,4,-5') (1, -2, 3, 4, -5) 
+6
source

Divide by , and go to int() :

 map(int, inputstring.split(',')) 

This creates a list; if you need a tuple, just wrap it with tuple() :

 tuple(map(int, inputstring.split(','))) 

In Python 3, map() returns a generator, so you should use a list view to create a 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) 
+4
source

Another way:

 >>> inputlist = '1,-2,3,4,-5' >>> tuple(int(x) for x in inputlist.split(',')) (1, -2, 3, 4, -5) >>> 
+1
source

Source: https://habr.com/ru/post/1496334/


All Articles