Python (re)

Whitespace Trim (Leading & Trailing) in PY

Match leading and/or trailing whitespace on a string — the regex equivalent of .trim().

Try it in the PY tester →

Pattern

regexPY
^\s+|\s+$   (flags: g)

Python (re) code

pyPython
import re

pattern = re.compile(r"^\s+|\s+$")
input_text = "  hello world  "
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

^\s+ matches one or more whitespace characters at the start of the string. \s+$ matches one or more whitespace characters at the end. The alternation | with the g flag allows replacing both in a single pass.

Examples

Input

hello world

Matches

Input

tabbed

Matches

Input

no padding

No match

Same pattern, other engines

← Back to Whitespace Trim (Leading & Trailing) overview (all engines)