Fight Fire With Fire Fight Fire With Fire - 1 year ago 87
Python Question

Separate Strings with quotes around them from strings without in Python

I have a string from a database field thats like this i bring into a varible words:

spaceship cars boats "subway train" rocket bicycle "18 wheeler"

if i do a split on string with this:

words = string.split()

I get results like this:

['spaceship', 'cars', 'boats', "'subway", "train'", 'rocket', 'bicycle', "'18", "wheeler'"]

what I would like is to split it to a list with the quoted words in tact so the list would look like this:

['spaceship', 'cars', 'boats', "'subway train'", 'rocket', 'bicycle', "'18 wheeler'"]

Is there a way tto processes this this way in python

Answer Source

You can also use shlex module:

>>> x
'spaceship cars boats "subway train" rocket bicycle "18 wheeler"'
>>> import shlex
>>> shlex.split(x)
['spaceship', 'cars', 'boats', 'subway train', 'rocket', 'bicycle', '18 wheeler']

Another solution would be using regex in this form:

import re
re.split(your_regular_exp, x)

but this is not as simple as with shlex but may prove usefull in other cases!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download