Reputation: 1686
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
Upvotes: 0
Views: 51
Reputation: 12972
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!
Upvotes: 2
Reputation: 599550
I think CSV is probably your friend here.
import csv
row = 'spaceship cars boats "subway train" rocket bicycle "18 wheeler"'
reader = csv.reader([row], delimiter=' ')
words = next(reader)
Upvotes: 1