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.