How do I trim whitespace from a string?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python, trimming whitespace usually means removing spaces, tabs, or newline characters from the beginning and end of a string. The standard tool for this is strip(), with lstrip() and rstrip() for one-sided trimming.
Use strip() for Both Ends
The most common case is removing leading and trailing whitespace at the same time.
This removes surrounding whitespace but keeps the content in the middle unchanged.
That last point matters. strip() is not a general “remove all spaces everywhere” function. It only works on the edges of the string.
Use lstrip() or rstrip() for One Side Only
If you only want to trim one side, use the directional versions.
This is useful when alignment or formatting rules require preserving whitespace on one side.
What Counts as Whitespace
By default, Python trimming methods remove common whitespace characters such as:
- spaces
- tabs
- newlines
- carriage returns
For example:
This behavior is usually what you want when cleaning user input, file lines, or command output.
strip() Does Not Remove Internal Spaces
A very common misunderstanding is expecting:
to become:
It does not. It becomes:
The spaces in the middle remain.
If you want to normalize internal whitespace too, you need a separate step:
That both trims the ends and compresses internal runs of whitespace to single spaces.
Trimming Specific Characters
strip() can also remove specific characters, not just default whitespace.
This removes * characters from both ends.
Be careful, though. strip("*") does not mean “remove the exact substring "***" from both ends.” It means “remove any * characters repeatedly from both ends until a different character appears.”
The same principle applies to multiple characters:
This removes any combination of a, b, or c from the ends, not the exact sequence "abc".
Common Input-Cleaning Pattern
A very typical Python pattern is trimming a line from a file or input field before validation:
This avoids bugs where a value looks non-empty but only contains whitespace around a meaningful core.
It is especially useful for:
- form inputs
- CSV parsing
- command-line arguments
- log processing
Unicode and Newer Alternatives
For ordinary Python text cleaning, strip() is already the right default. You generally do not need a third-party library just to remove surrounding whitespace.
If your data contains unusual Unicode spacing characters, test explicitly with real input, but the built-in string methods handle the vast majority of normal text-cleaning cases well.
Common Pitfalls
The most common pitfall is expecting strip() to remove spaces inside the string. It only trims the ends.
Another mistake is using strip("abc") and assuming it removes the exact substring "abc" from each side. It removes any of those individual characters at the boundaries.
A third issue is trimming input and then forgetting to use the cleaned result. Since strings are immutable, strip() returns a new string rather than modifying the original one in place.
Finally, developers sometimes overcomplicate simple whitespace cleanup with regular expressions when strip() already solves the real problem.
Summary
- Use
strip()to remove leading and trailing whitespace in Python. - Use
lstrip()orrstrip()when only one side should be trimmed. - '
strip()does not remove internal whitespace.' - Passing characters to
strip()removes those boundary characters, not an exact substring. - Remember to store the returned string because Python strings are immutable.
Related reading
- How do I turn a python datetime into a string, with readable format date?
- How do I type hint a method with the type of the enclosing class?
- How do I type hint a method with the type of the enclosing class?
- How do I unload (reload) a Python module?
- How do I unload reload a Python module?
- How do I update a Python package?
- How do I update Anaconda?
- How do I update/upgrade pip itself from inside my virtual environment?
.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.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.