-2

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?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Y.Johri
  • 11
  • Also see http://stackoverflow.com/questions/743806/split-string-into-a-list-in-python and [str.split method](https://docs.python.org/2/library/stdtypes.html#str.split) documentation. – Mazdak Aug 12 '15 at 16:25

2 Answers2

1

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)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

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)
vaultah
  • 44,105
  • 12
  • 114
  • 143