How do I remove leading whitespace in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Removing leading whitespace in Python is usually a one-method job, but the right method depends on whether you are cleaning a single string, processing many lines, or preserving relative indentation in a block of text. For most cases, lstrip() is the correct default because it removes whitespace only from the start of the string.
Use lstrip() for Ordinary String Cleanup
str.lstrip() removes leading whitespace and leaves the rest of the string alone.
This is the safest choice when you want to normalize left alignment without touching trailing spaces or internal formatting.
You can also pass characters to lstrip():
That is useful, but there is an important detail: the argument is treated as a set of characters, not an exact prefix. So lstrip("ab") removes any leading a and b characters in any order until it hits something else.
Know the Difference Between lstrip(), rstrip(), and strip()
These methods are easy to confuse, and using the wrong one can silently change data.
Use:
- '
lstrip()when you only want to remove leading whitespace' - '
rstrip()when you only want to remove trailing whitespace' - '
strip()when you want both'
If the input format cares about trailing spaces, strip() may be too aggressive.
Handle Multiline Text with textwrap.dedent
For multiline strings, lstrip() on the whole string is often not enough. If your goal is to remove common indentation while keeping the relative structure of the block, textwrap.dedent() is a better fit.
This is especially useful for SQL, templates, help text, and code snippets embedded in Python source.
If you need to process each line independently, use a loop:
That approach works well for file cleanup jobs and ETL pipelines.
Use Regular Expressions for Custom Rules
Sometimes "remove leading whitespace" really means "remove only spaces, not tabs" or "strip indentation only after a prefix". That is where regular expressions help.
This removes leading spaces but leaves the tab intact.
For multiline text:
Use regex only when built-in string methods are too broad. For standard cleanup, lstrip() is clearer and faster.
Common Pitfalls
The most common mistake is using strip() when only left-side whitespace should be removed. That also deletes trailing whitespace, which may be meaningful in some formats.
Another common issue is misunderstanding lstrip(chars). It does not remove an exact prefix string. It removes any leading characters that appear in the provided set.
People also accidentally destroy indentation in content where whitespace matters, such as Python code samples, YAML, or Markdown code blocks. In those cases, remove whitespace only after deciding which indentation is structural and which is accidental.
Finally, if you clean strings in several different places, behavior can drift. It is often better to normalize input at one boundary and keep the rest of the program working with already-clean values.
Summary
- Use
lstrip()to remove leading whitespace from a normal Python string. - Use
rstrip()orstrip()only when the right side should also be changed. - Use
textwrap.dedent()for multiline blocks with common indentation. - Use regex for special cases such as removing only spaces or processing each line with custom rules.
- Be careful with indentation-sensitive text, because aggressive stripping can change meaning.
Related reading
- How do I remove NaN values from a NumPy array?
- How do I remove packages installed with Python's easy_install?
- How do I remove the first item from a list?
- How do I remove the first item from a list?
- How do I remove whitespace from the end of a string in Python?
- How do I remove/delete a virtualenv?
- How do I remove/delete a virtualenv?
- How do I resize an image using PIL and maintain its aspect ratio?
.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.