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.