robbie james
robbie james

Reputation: 41

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?

Upvotes: 4

Views: 1277

Answers (3)

Martijn Pieters
Martijn Pieters

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

user2555451
user2555451

Reputation:

Another way:

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

Upvotes: 1

agf
agf

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

Related Questions