How to remove whitespace from a string in Python using the `strip()` method?

Published on Aug. 22, 2023, 12:17 p.m.

To remove whitespace from a string in Python using the strip() method, you can call the strip() method on the string. This method will remove all leading and trailing whitespace characters from the string.

Here’s an example:

my_string = "     hello world       "
print(my_string.strip())

Output:

"hello world"

In this example, we have defined a string with leading and trailing whitespace characters. We then call the strip() method on the string to remove the whitespaces, and print the result.

There are also other related methods like lstrip() and rstrip() that remove whitespace only from the left or right side of the string respectively.

Note that strip() creates a new string, and does not modify the original string. If you want to modify the original string, you can re-assign the result of the strip() method back to the original variable.

Tags: