Strip spaces

2 snippets across 2 stacks - Python, Regular Expressions

Also written as strip whitespace

PYPython

Common String Methods

PY · Strings
Syntax
str.method()
Example
email = "  [email protected]  "
print(email.strip().lower())
print("hello world".title())
print("python".startswith("py"))
print("2026-04-04".replace("-", "/"))
Output
[email protected]
Hello World
True
2026/04/04

Note String methods always return new strings since strings are immutable. Chain methods for compact transformations.

RXRegular Expressions

Whitespace Trimming

RX · Common Patterns
Syntax
/^\s+|\s+$/g
Example
JS:  '  hello world  '.replace(/^\s+|\s+$/g, '')
Py:  re.sub(r'^\s+|\s+$', '', '  hello world  ')
Output
"hello world"

Note Equivalent to str.trim() in JS and str.strip() in Python. The regex version is useful when you also want to normalize internal whitespace: replace /\s+/g with ' ' after trimming.

Frequently asked questions

How does Python handle strip spaces?
This task is covered in 2 stacks on this page: Python, Regular Expressions. The "Common String Methods" snippet in Python uses `str.method()`.
Which code does the Python example use?
The "Common String Methods" snippet uses `str.method()`, from the Strings section of the Python cheat sheet.
Which stacks cover "strip spaces" on this page?
Python, Regular Expressions. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Common String Methods": String methods always return new strings since strings are immutable. Chain methods for compact transformations.