Splitting strings in Python while not ignoring escape characters

Splitting strings in Python is easy:

"this is a string".split() # default delimiter is a space (' ')
# ['this', 'is', 'a', 'string']

However, when your faced with escape characters, things become a tad more difficult:

"this is\ a string".split()
# ['this', 'is\\', 'a', 'string']

Of course you could write your own split function that takes care of these escape characters, but there’s an easier way still:

import cStringIO as c
import csv
csv.reader(c.StringIO("this is\ a string"), delimiter=' ', escapechar='\\').next()
# ['this', 'is a', 'string']
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>