string - Python - Most elegant way to extract a substring, being given left and right borders -
i have string - python :
string = "/foo13546897/bar/atlantis-gps-coordinates/bar457822368/foo/"
expected output :
"atlantis-gps-coordinates"
i know expected output surrounded "/bar/" on left , "/" on right :
"/bar/atlantis-gps-coordinates/"
proposed solution :
a = string.find("/bar/") b = string.find("/",a+5) output=string[a+5,b]
this works, don't it. know beautiful function or tip ?
you can use split:
>>> string.split("/bar/")[1].split("/")[0] 'atlantis-gps-coordinates'
some efficiency adding max split of 1
suppose:
>>> string.split("/bar/", 1)[1].split("/", 1)[0] 'atlantis-gps-coordinates'
or use partition:
>>> string.partition("/bar/")[2].partition("/")[0] 'atlantis-gps-coordinates'
or regex:
>>> re.search(r'/bar/([^/]+)', string).group(1) 'atlantis-gps-coordinates'
depends on speaks , data.
Comments
Post a Comment