Trim white spaces from String in Python


Python - Trim string

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 to trim whitespaces from a given string.

Pytho Strip or Trim Whitespaces in String

Examples

1. Trim whitespaces from edges of given 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))

Output

   python examples
26

python examples
15

2. Trim whitespaces 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))

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.