
PYTHON — Remove Whitespace Exercise in Python
Artificial intelligence is growing up fast, as are robots whose facial expressions can elicit empathy and make your mirror neurons quiver. — Diane Ackerman
In this exercise, we will write a Python program to remove whitespace from strings and print out the modified strings. We are given three strings with varying amounts of whitespace, and our task is to clean them up.
Let’s start by defining the strings and then removing the whitespace:
# Define the strings
string1 = " Filet Mignon"
string2 = "Cheesecake "
string3 = " French Fries "
# Remove the whitespace from the strings and print them
print(string1.strip())
print(string2.strip())
print(string3.strip())When we run this program, the output will be:
Filet Mignon
Cheesecake
French FriesIn the code snippet above, we use the strip() method to remove leading and trailing whitespace from each string. This method returns a copy of the string with the leading and trailing whitespace removed.
Now, let’s break down the code:
- We define three strings
string1,string2, andstring3with varying amounts of whitespace. - We then use the
strip()method on each string to remove the whitespace. - Finally, we print the modified strings to see the whitespace-free versions.
By using the strip() method, we have successfully removed the leading and trailing whitespace from the given strings.
This exercise is a simple demonstration of using string methods in Python to manipulate and clean up textual data. The strip() method is just one of many string methods available in Python for string manipulation.






