How do I remove leading and trailing whitespace from a string in Python?
" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
pythonstringtrim
How do I remove leading and trailing whitespace from a string in Python?
" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
Best Answer
To remove all whitespace surrounding a string, use
.strip()
. Examples:Note that
str.strip()
removes all whitespace characters, including tabs and newlines. To remove only spaces, specify the specific character to remove as an argument tostrip
:To remove only one space at most: