python re - split a string before a character


Question

how to split a string at positions before a character?

  • split a string before 'a'
  • input: "fffagggahhh"
  • output: ["fff", "aggg", "ahhh"]

the obvious way doesn't work:

>>> h=re.compile("(?=a)")

>>> h.split("fffagggahhh")

['fffagggahhh']

>>>
1
12
11/4/2010 6:36:49 AM

Ok, not exactly the solution you want but I thought it will be a useful addition to problem here.

Solution without re

Without re:

>>> x = "fffagggahhh"
>>> k = x.split('a')
>>> j = [k[0]] + ['a'+l for l in k[1:]]
>>> j
['fff', 'aggg', 'ahhh']
>>> 
20
11/4/2010 6:39:06 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon