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