String splitting by spaces question

Jerry Hill malaclypse2 at gmail.com
Wed Nov 23 13:34:39 EST 2011


On Wed, Nov 23, 2011 at 12:10 PM, Massi <massi_srb at msn.com> wrote:

> Hi everyone,
>
> I have to parse a string and splitting it by spaces. The problem is
> that the string can include substrings comprises by quotations which
> must mantain the spaces. What I need is to pass from a string like:
>
> This is an 'example string'
>
> to the following vector:
>
> ["This", "is", "an", "example string"]
>
> Which is the best way to achieve this?
>


This sounds a lot like the way a shell parses arguments on the command
line.  If that's your desire, python has a module in the standard library
that will help, called shlex (http://docs.python.org/library/shlex.html).
Particularly, shlex.split may do exactly what you want out of the box:

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit
(Intel)] on win32

>>> import shlex
>>> s = "This is an 'example string'"
>>> shlex.split(s)
['This', 'is', 'an', 'example string']
>>>

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111123/fc7e972f/attachment.html>


More information about the Python-list mailing list