Google News
logo
Python Program to Remove whitespace from the beginning or at the end of a string
In the following example of Python program that demonstrates how to remove whitespace from the beginning or at the end of a string :
Program :
# Remove whitespace from the beginning or at the end of a string
my_string = "   Hello, World!   "
print("Original string:", my_string)

trimmed_string = my_string.strip()
print("Trimmed string:", trimmed_string)
Output :
Original string:    Hello, World!   
Trimmed string: Hello, World!
In the above program, we start by assigning the string value `"   Hello, World!   "` to the variable `my_string`. We then use the `print()` function to print the original value of `my_string`.

Next, we use the `strip()` method to remove any whitespace characters from the beginning or at the end of `my_string`. We assign the result of this operation to the variable `trimmed_string`.

Finally, we use the `print()` function to print the trimmed string.

As you can see, the whitespace characters from the beginning and end of the original string have been removed from the trimmed string.