How do I trim whitespace?

 

To trim whitespace from a string in Python, you can use the strip() method, which removes leading and trailing whitespace (spaces, tabs, and newline characters) from the string. Here's an example:

python
# Original string with leading and trailing whitespace original_string = " Hello, World! " # Trim whitespace from the string trimmed_string = original_string.strip() # Print the trimmed string print(trimmed_string)

In this example, we start with an original_string that contains leading and trailing whitespace. We then use the strip() method to remove the whitespace, and the result is stored in the trimmed_string variable.

When you run this code, the output will be:

Hello, World!

As you can see, the strip() method removed the leading and trailing spaces, leaving only the content of the string.

If you want to remove only leading or trailing whitespace (not both), you can use the lstrip() method to remove leading whitespace or the rstrip() method to remove trailing whitespace:

python
# Original string with leading and trailing whitespace original_string = " Hello, World! " # Remove leading whitespace leading_trimmed_string = original_string.lstrip() # Remove trailing whitespace trailing_trimmed_string = original_string.rstrip() # Print the results print("Leading Trimmed String:", leading_trimmed_string) print("Trailing Trimmed String:", trailing_trimmed_string)

This code will produce the following output:

arduino
Leading Trimmed String: Hello, World! Trailing Trimmed String: Hello, World!

As shown, the lstrip() method removes leading whitespace, and the rstrip() method removes trailing whitespace, leaving the other whitespace intact.

Comments