Question

This is simple string manipulation in python:

string = '<longitude>-170.794865296</longitude>'

How can i extract -170.794865296? Looking for simple and easy way.

Was it helpful?

Solution 2

string.split(">")[1].split("<")[0]

No need to import anything

OTHER TIPS

You can use xml.etree.ElementTree from the standard library:

>>> import xml.etree.ElementTree as etree
>>> s = '<longitude>-170.794865296</longitude>'
>>> etree.fromstring(s).text
'-170.794865296'
import re
print re.findall(r'[-0-9.]+', '<longitude>-170.794865296</longitude>')

If your numbers are all formatted using the '<longitude>...</longitude>' tag, then you could just use string slicing:

start = len('<longitude>')
end = -len('</longitude>')
print float('<longitude>-170.48738723</longitude>'[start:end])

Using parse module

$ pip install parse

to impress you by brevity:

>>> from parse import parse
>>> parse("<lon>{:f}</lon>", "<lon>-170.794865296</lon>").fixed[0]
-170.794865296

to explain it step by step

>>> from parse import parse
>>> text = '<lon>-170.794865296</lon>'
>>> templ = "<lon>{:f}</lon>"
>>> res = parse(templ, text)
>>> res
<Result (-170.794865296,) {}>
>>> res.fixed[0]
-170.794865296
>>> type(res.fixed[0])
float

assign values to dictionary keys:

>>> parse("<lon>{pnt_lat:f}</lon>", "<lon>-170.794865296</lon>").named["pnt_lat"]
-170.794865296
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top