Python Program to Trim Whitespace From a String Ad Sponsored

ⓘ Sponsored by

In programming, whitespace refers to any non-printing character like spaces, tabs, or newline characters. When we read data from user input or from a file, sometimes it contains unwanted leading or trailing whitespace characters. This can cause issues when we want to use the data, especially if we need to compare or manipulate strings.

Trimming whitespace means removing these leading or trailing whitespace characters from a string.

Python Code :

The below Python program trims whitespace from a string:

# Define a string with leading and trailing whitespace
my_string = "    Hello, World!   "

# Trim leading and trailing whitespace using the strip() method
trimmed_string = my_string.strip()

# Print the original string and the trimmed string
print("Original string:", my_string)
print("Trimmed string:", trimmed_string)

In this program, we first define a string my_string with leading and trailing whitespace.

To trim the whitespace from the string, we call the strip() method on the string. The strip() method removes any leading or trailing whitespace characters (spaces, tabs, and newlines) from the string, and returns the resulting string.

We then assign the resulting trimmed string to a new variable trimmed_string.

Finally, we print both the original string and the trimmed string using the print() function. This demonstrates that the strip() method has removed the leading and trailing whitespace from the string. Ad Sponsored

ⓘ Sponsored by