DEV Community

Cover image for How do I trim whitespace from a string in Python?
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

2 1

How do I trim whitespace from a string in Python?

When working with Python strings, a pretty common question is how to trim whitespace from a string. Whitespace characters are the space (), tab (\t), newline (\n), and carriage return characters (\r). Here are 3 different methods to trim whitespace from a string in Python.

Remove leading and trailing whitespace characters

Use the str.strip() method to remove whitespace characters from both the beginning and end of a string.

'  Hello  '.strip()    # 'Hello'
Enter fullscreen mode Exit fullscreen mode

Remove leading whitespace characters

Leading whitespace characters are the whitespace characters at the start of a string. To remove them, use the str.lstrip() method.

'  Hello  '.lstrip()   # 'Hello  '
Enter fullscreen mode Exit fullscreen mode

Remove trailing whitespace characters

Trailing whitespace characters are the whitespace characters at the end of a string. To remove them, use the str.rstrip() method.

'  Hello  '.rstrip()   # '  Hello'
Enter fullscreen mode Exit fullscreen mode

Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay