Programming
String Manipulation
Coding Tutorial
Whitespace Trimming
Python

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.

Browse interview questions

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.

python
1text = "   Hello, world!   \n"
2clean = text.strip()
3
4print(repr(clean))

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.

python
1text = "   Hello, world!   "
2
3print(repr(text.lstrip()))
4print(repr(text.rstrip()))

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:

python
text = "\t  hello\n"
print(repr(text.strip()))

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:

python
"  hello   world  ".strip()

to become:

text
helloworld

It does not. It becomes:

text
hello   world

The spaces in the middle remain.

If you want to normalize internal whitespace too, you need a separate step:

python
1text = "  hello   world  "
2normalized = " ".join(text.split())
3
4print(repr(normalized))

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.

python
text = "***hello***"
print(text.strip("*"))

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:

python
text = "abcHelloacb"
print(text.strip("abc"))

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:

python
1username = "   alice   "
2username = username.strip()
3
4if username:
5    print("Valid username:", username)

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() or rstrip() 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
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.