Split a string by spaces -- preserving quoted substrings -- in Python
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Splitting a string by spaces while keeping quoted substrings intact is a common need when parsing command-line arguments, CSV-like data, or search queries. Python's str.split() breaks on every space, destroying quoted phrases. The standard library provides shlex.split() which handles this correctly, and csv.reader works for CSV-style quoting. Understanding when to use each saves you from writing fragile regex solutions.
The Problem
"foo bar" should stay together as one token, but split() does not understand quotes.
Method 1: shlex.split() (Recommended)
The shlex module parses strings using shell-like syntax, handling single quotes, double quotes, and escape characters:
shlex.split() removes the quotes and keeps the content together. It also handles:
Method 2: csv.reader
For CSV-style quoting (where only double quotes are special):
csv.reader handles doubled quotes for escaping ("" inside a quoted field becomes a single "):
Note: csv.reader may produce empty strings for consecutive spaces, unlike shlex.split().
Method 3: Regular Expressions
When you need custom quoting rules:
This regex has two alternatives:
"([^"]*)"— matches a double-quoted string and captures the content (without quotes)\S+— matches any non-space sequence
Method 4: Custom Parser
For full control, write a state-machine parser:
Comparison
| Method | Handles single quotes | Handles escapes | Empty tokens | Speed |
shlex.split() | Yes | Yes (backslash) | No | Moderate |
csv.reader | No | Yes (doubled "") | Yes | Fast |
| Regex | Configurable | Manual | No | Fast |
| Custom parser | Configurable | Configurable | Configurable | Varies |
Practical Examples
Parsing Search Queries
Parsing Command-Line Strings
Keeping Quotes in Output
If you need to preserve the quote characters:
Common Pitfalls
shlex.split()on Windows paths: Backslashes are treated as escape characters. Useshlex.split(text, posix=False)on Windows or raw strings to preserve backslashes.- Unclosed quotes:
shlex.split('hello "foo bar')raisesValueError: No closing quotation. Wrap in try/except or validate input first. - Empty strings between spaces:
csv.readerproduces empty strings for'a b'(two spaces) →['a', '', 'b']. Filter with[t for t in tokens if t]. - Unicode quotes:
shlex.split()does not recognize Unicode smart quotes (\u201c,\u201d). Replace them with ASCII quotes first:text.replace('\u201c', '"').replace('\u201d', '"'). - Performance on large input:
shlex.split()parses character-by-character and is slower thanstr.split(). For millions of lines, usecsv.readeror compiled regex.
Summary
- Use
shlex.split()for shell-like parsing with quote and escape support - Use
csv.readerwithdelimiter=' 'for CSV-style quoting - Use
re.findall(r'"([^"]*)"|\S+', text)for simple double-quote preservation shlex.split()removes quotes from output; use regex if you need to keep them- Handle edge cases: unclosed quotes, Windows backslashes, consecutive spaces
Related reading
- Split a string into pieces of max length X - split only at spaces
- Split on regex more than a character, maybe variable width and keep the separator like GNU awk
- Split string into words
- Split Strings into words with multiple word boundary delimiters
- Split a string into a list in Jinja
- Split explode pandas dataframe string entry to separate rows
- splitting a string based on multiple char delimiters
- Splitting a string into chunks of a certain size
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.