Split string by space and preserve quoted strings in Python


Borislav Hadzhiev

Last updated: Jun 24, 2022


Photo from Unsplash

Split string by space and preserve quoted strings in Python #

To split a string by space and preserve quoted substrings:

  1. Import the shlex module.
  2. Pass the string to the shlex.split() method.
  3. The shlex.split method splits the string using a shell-like syntax.
import shlex my_str = 'one "two" three "four"' # 👇️ ['one', 'two', 'three', 'four'] print(shlex.split(my_str)) # 👇️ ['one', '"two"', 'three', '"four"'] print(shlex.split(my_str, posix=False))

In the first example, we directly passed the string to the shlex.split method without providing any arguments.

By default the posix argument is set to True. When POSIX mode is enabled, the quotes are not kept after splitting the string.

The second example sets the posix argument to False to keep the quotes after splitting.

The shlex.split method also takes care of removing any leading or trailing spaces when splitting the string.

import shlex my_str = ' one "two" three "four" ' my_list = shlex.split(my_str) print(my_list) # 👉️ ['one', 'two', 'three', 'four']
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.