Python – Trim white spaces from String

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))
Run Code Copy

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))
Run Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍