Search This Blog

Thursday, September 15, 2011

HowTo: Split Python strings with multiple separators

Python strings split with multiple separators - Stack Overflow

What to you do if each caller uses a different delimiter to list multiple integers in a string?

While the above link is nice, it doesn't treat punctuation as a delimiter to split, so 123:123 becomes 123123.

The right answer is subtle, but works:
import string,re
thestring = "Hey, you - what are you doing 123:456 here!?"
print re.sub('['+string.punctuation+']',' ',thestring).split()


http://docs.python.org/library/re.html


Assume they will use punctuation as a delimiter...Not perfect, but true in my case today.

import string
thestring = " 1234 234 345345 123:234:345:"
s=list(thestring)
print ''.join([ o for o in s if not o in string.punctuation ]).split()

No comments:

Post a Comment