Python
whitespace
string manipulation
strip
programming tips

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.

Browse interview questions

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.

python
1text = "\t   hello world   "
2clean = text.lstrip()
3
4print(repr(text))
5print(repr(clean))

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():

python
value = "---title"
print(value.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.

python
1text = "   data   "
2
3print(repr(text.lstrip()))
4print(repr(text.rstrip()))
5print(repr(text.strip()))

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.

python
1import textwrap
2
3query = """
4        SELECT id, name
5        FROM users
6        WHERE active = 1
7"""
8
9normalized = textwrap.dedent(query).strip()
10print(normalized)

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:

python
lines = ["   one", "\ttwo", "    three"]
cleaned = [line.lstrip() for line in lines]
print(cleaned)

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.

python
1import re
2
3text = "\t   keep-tab"
4clean = re.sub(r"^ +", "", text)
5print(repr(clean))

This removes leading spaces but leaves the tab intact.

For multiline text:

python
1import re
2
3text = "  a\n\tb\n    c"
4clean = re.sub(r"(?m)^\\s+", "", text)
5print(clean)

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() or strip() 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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.