Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Most elegant way to extract a substring, being given left and right borders [duplicate]

I have a string - Python :

string = "/foo13546897/bar/Atlantis-GPS-coordinates/bar457822368/foo/"

Expected output is :

"Atlantis-GPS-coordinates"

I know that the expected output is ALWAYS surrounded by "/bar/" on the left and "/" on the right :

"/bar/Atlantis-GPS-coordinates/"

Proposed solution would look like :

a = string.find("/bar/")
b = string.find("/",a+5)
output=string[a+5,b]

This works, but I don't like it. Does someone know a beautiful function or tip ?

like image 572
Vincent Avatar asked Jan 17 '16 01:01

Vincent


1 Answers

You can use split:

>>> string.split("/bar/")[1].split("/")[0]
'Atlantis-GPS-coordinates'

Some efficiency from adding a max split of 1 I 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 a regex:

>>> re.search(r'/bar/([^/]+)', string).group(1)
'Atlantis-GPS-coordinates'

Depends on what speaks to you and your data.

like image 124
dawg Avatar answered Sep 22 '22 17:09

dawg