Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split multi-line string with shlex and keep quote characters

How do I split a string with Python's shlex while preserving the quote characters that shlex splits on?

Sample Input:

Two Words
"A Multi-line
 comment."

Desired Output:

['Two', 'Words', '"A Multi-line\ncomment."']

Note the double quotes wrapping the multi-line string. I read through the shlex documentation, but I don't see an obvious option. Does this require a regular expression solution?

like image 529
Petrus Theron Avatar asked Dec 23 '13 23:12

Petrus Theron


Video Answer


1 Answers

>>> print(s)
Two Words
"A Multi-line
 comment."
>>> shlex.split(s)
['Two', 'Words', 'A Multi-line\n comment.']
>>> shlex.split(s, posix=False)
['Two', 'Words', '"A Multi-line\n comment."']
>>> 

Changed in version 2.6: Added the posix parameter.

like image 57
kxr Avatar answered Sep 19 '22 19:09

kxr