Sachin Sachin - 6 months ago 11
Python Question

Deleting all occurances of / after its 2nd occurance in python

I have a URL which is https://example.com/about/hello/

I want to split string as 'https://example.com', 'about' ,'hello' how to do this ??

Answer

There are lots of ways to do this. You could use re.split() to split on a regular expression, for instance.

>>> import re
>>> re.split(r'\b/\b', 'https://example.com/about/hello/')
['https://example.com', 'about', 'hello']

re is part of the standard library, documented here. https://docs.python.org/3/library/re.html#re.split The regex itself uses \b which means a boundy between a "word" character and a "non-word" character. You can use regex101 to explore how it works. https://regex101.com/r/mY8fV8/1

Comments