Python Forum
str.split() with separator grouping
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
str.split() with separator grouping
#1
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']
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Use re.split()
>>> import re
>>> foo = '/usr///bin///bar'
>>> re.split(r'/+', foo)
['', 'usr', 'bin', 'bar']
>>> 
Skaperen likes this post
« We can solve any problem by introducing an extra level of indirection »
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020