Python Forum
str.split() with separator grouping - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: str.split() with separator grouping (/thread-41290.html)



str.split() with separator grouping - Skaperen - Dec-14-2023

if sep is not given when calling str.split(), it combines runs of white-space as a single separator. if sep is given, then each character is a separator and empty strings can result when there are runs of the same character.

what i am looking for (to avoid implementing this) is a split() (and rsplit() variant) that can group runs of the same specified separator string together as a single separator. i will be doing this from back to front so i will be wanting an rsplit() variant of it.

for example, calling it gsplit:
foo = '/usr///bin///bar'
bar = whatever.gsplit(foo,'/')
print(repr(bar))
Output:
[ '','usr','bin','bar']



RE: str.split() with separator grouping - Gribouillis - Dec-14-2023

Use re.split()
>>> import re
>>> foo = '/usr///bin///bar'
>>> re.split(r'/+', foo)
['', 'usr', 'bin', 'bar']
>>>