I have a string like this:
'5100387, 54.799831647418, -4.147024550067, 22.466648807633'
I want to get a tuple from it:
(5100387, 54.799831647418, -4.147024550067, 22.466648807633)
How to do it?
I have a string like this:
'5100387, 54.799831647418, -4.147024550067, 22.466648807633'
I want to get a tuple from it:
(5100387, 54.799831647418, -4.147024550067, 22.466648807633)
How to do it?
You can split
on commas and use a generator expression to convert each item to float
, then create a tuple
from that.
>>> tuple(float(i) for i in s.split(','))
(5100387.0, 54.799831647418, -4.147024550067, 22.466648807633)
Similarly map
can do the same thing
>>> tuple(map(float, s.split(',')))
(5100387.0, 54.799831647418, -4.147024550067, 22.466648807633)
Your string contains a valid tuple literal. You could give ast.literal_eval
a try:
In [1]: import ast
In [2]: ast.literal_eval('5100387, 54.799831647418, -4.147024550067, 22.466648807633')
Out[2]: (5100387, 54.799831647418, -4.147024550067, 22.466648807633)
or split by ', '
and convert each element of the list to float (or something else):
In [4]: tuple(map(float, s.split(', ')))
Out[4]: (5100387.0, 54.799831647418, -4.147024550067, 22.466648807633)