Python Remove Whitespace from Both Ends of a String
In Python, you can use the strip() method to remove whitespace characters (including spaces, tabs and newlines) from both ends of a string. This method returns a new string; the original string is not modified.
Example
text
=
" Hello, World! "
trimmed_text
=
text.
strip
(
)
(
f
"Original: '{text}'"
)
(
f
"Trimmed: '{trimmed_text}'"
)
Code analysis:
text = " Hello, World! ": Define a string containing leading and trailing whitespace.trimmed_text = text.strip(): When usingstrip()The method removes the whitespace from both ends and assigns the result totrimmed_text。print(f"Original: '{text}'"): Print the original string for comparison.print(f"Trimmed: '{trimmed_text}'"): Print the string after the whitespace is removed.
Output result:
Original: ' Hello, World! '
Trimmed: 'Hello, World!'
Python3 Examples