Python Strip() – Remove White Spaces at Start and End of String

Python String.strip()

To remove the spaces present at start and end of the string, you can use strip() function on the string.

In this tutorial, we will go through examples that demonstrate how to use String.strip() function.

Pytho Strip or Trim Whitespaces in String

Example 1: Trim White Spaces around String

In the following example, we assign a variable with a string that has spaces at start and end of it. Then we use strip() function to remove the spaces around the string.

Python Program

mystring = '   python examples        '

cleanstring = mystring.strip()

# before strip
print(mystring)
print(len(mystring))

# after string
print(cleanstring)
print(len(cleanstring))
Run

Output

   python examples
26

python examples
15

Example 2: Trim White Spaces like \n \t around String

In the following example, we take a string that has new line character and tab spaces at the beginning and ending of it. Then we use strip() function to remove these whitespace characters around the string.

Python Program

mystring = ' \n\t  python examples \n\n'

cleanstring = mystring.strip()

# before strip
print(mystring)
print(len(mystring))

# after string
print(cleanstring)
print(len(cleanstring))
Run

Output


          python examples


23
python examples
15

All the white space characters have been removed from the edges of string.

Summary

In this tutorial of Python Examples, we learned to trim or strip the white space characters for a string.