Skip to content

Python coding : get string between two characters #21422

Python coding : get string between two characters #21422
Nov 27, 2021 · 2 answers

I want to get a substring between two characters (/ and ?) from some url I have
For example, I have : https://partners.doctolib.fr/vaccination-covid-19/rennes/centre-de-vaccination-covid-19-rennes-school-of-business-rennes?pid=practice-205813&enable_cookies_consent=1 and I need to have just “centre-de-vaccination-covid-19-rennes-school-of-business-rennes”

I tried with split(’/, ?’) and split(’/’, ‘?’) but it doesn’t work

Take a look at regular expressions (the re module). They allow you to specify a pattern and match a string or parts of it against that pattern:

>>> import re
>>> url = 'https://partners.doctolib.fr/vaccination-covid-19/rennes/centre-de-vaccination-covid-19-rennes-school-of-business-rennes?pid=practice-205813&enable_cookies_consent=1'
>>> r = re.compile(r'/([^/\?]+)\?')
>>> m = r.search(url)
>>> m.group(1)
'centre-de-vaccination-covid-19-rennes-school-of-business-rennes'

The exact pattern depends on what exactly you’re looking for, the one I wrote searches for a /, a group of one or more characters that aren’t / or ?, and finally a ?. The group is defined by parentheses, and is helpful be…

Replies

2 suggested answers

Take a look at regular expressions (the re module). They allow you to specify a pattern and match a string or parts of it against that pattern:

>>> import re
>>> url = 'https://partners.doctolib.fr/vaccination-covid-19/rennes/centre-de-vaccination-covid-19-rennes-school-of-business-rennes?pid=practice-205813&enable_cookies_consent=1'
>>> r = re.compile(r'/([^/\?]+)\?')
>>> m = r.search(url)
>>> m.group(1)
'centre-de-vaccination-covid-19-rennes-school-of-business-rennes'

The exact pattern depends on what exactly you’re looking for, the one I wrote searches for a /, a group of one or more characters that aren’t / or ?, and finally a ?. The group is defined by parentheses, and is helpful because you can access matched groups in the Match object (m here).

0 replies
Answer selected
text = "https://partners.doctolib.fr/vaccination-covid-19/rennes/centre-de-vaccination-covid-19-rennes-school-of-business-rennes?pid=practice-205813&enable_cookies_consent=1"

parts1 = text.split('?')
parts2 = parts1[0].split('/')
print(parts2[-1])
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
General
Labels
None yet
3 participants