Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: elegant and code saving way to split an string in a list

i have a string as:

mydata
'POINT (558750.3267372231900000 6361788.0628051758000000)'

i wish a code saving way to convert in a list numeric as

(g, (x,y)) 

where:

g = geometry (POINT)
x = coordinates x
y = coordinates y

i am using

mydata.split(" ")
['POINT', '(558750.3267372231900000', '6361788.0628051758000000)']

but after that i need to use several code line to get x and y

like image 788
Gianni Spear Avatar asked Jan 27 '26 03:01

Gianni Spear


2 Answers

Step by step:

>>> s = 'POINT (558750.3267372231900000 6361788.0628051758000000)'
>>> word, points = s.split(None, 1)
>>> word
'POINT'
>>> points
'(558750.3267372231900000 6361788.0628051758000000)'
>>> points = points.strip('()').split()
>>> points
['558750.3267372231900000', '6361788.0628051758000000']
>>> x, y = (float(i) for i in points)
>>> x
558750.3267372232
>>> y
6361788.062805176
like image 101
Jon Clements Avatar answered Jan 28 '26 16:01

Jon Clements


Regex can spare you some typing here:

In [1]: import re

In [2]: def nice_tuple(s):                                                    
    g, x, y, _ = re.split(' ?[()]?', s)
    return g, tuple(map(float, (x, y)))
   ...: 

In [3]: nice_tuple('POINT (558750.3267372231900000 6361788.0628051758000000)')
Out[3]: ('POINT', (558750.3267372232, 6361788.062805176))
like image 38
Lev Levitsky Avatar answered Jan 28 '26 15:01

Lev Levitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!