HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

How do I trim whitespace from a string in Python?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
fromtrimhowwhitespacepythonstring

Problem

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.
Use the str.strip() method to remove whitespace characters from both the beginning and end of a string.
Leading whitespace characters are the whitespace characters at the start of a string. To remove them, use the str.lstrip() method.
Trailing whitespace characters are the whitespace characters at the end of a string. To remove them, use the str.rstrip() method.

Solution

'  Hello  '.strip()    # 'Hello'


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

Code Snippets

'  Hello  '.strip()    # 'Hello'
'  Hello  '.lstrip()   # 'Hello  '
'  Hello  '.rstrip()   # '  Hello'

Context

From 30-seconds-of-code: trim-whitespace

Revisions (0)

No revisions yet.