Python Program - Trim Whitespace From a String
Here's a Python program that trims whitespace from a string:
# Define a string with whitespace string = " Hello, World! " # Trim whitespace from the beginning and end of the string trimmed = string.strip() # Print the original and trimmed strings print("Original string: '{}'\nTrimmed string: '{}'".format(string, trimmed))
In this program, we define a string with whitespace at the beginning and end: " Hello, World! "
. We then use the strip()
method to remove the whitespace from the beginning and end of the string, producing the trimmed string: "Hello, World!"
.
Finally, we print both the original and trimmed strings using string formatting with the format()
method.
If we run this program, the output will be:
Original string: ' Hello, World! ' Trimmed string: 'Hello, World!'
Note that the strip()
method only removes whitespace from the beginning and end of a string. If you want to remove whitespace from the beginning, end, and middle of a string, you can use the replace()
method to replace all instances of whitespace with an empty string:
# Define a string with whitespace string = " Hello, World! " # Remove all whitespace from the string trimmed = string.replace(" ", "") # Print the original and trimmed strings print("Original string: '{}'\nTrimmed string: '{}'".format(string, trimmed))
This program produces the output:
Original string: ' Hello, World! ' Trimmed string: 'Hello,World!'