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))

Explanation

  1. The strip() method removes all leading and trailing whitespace characters from mystring, which in this case includes spaces before and after the string "python examples".
  2. Before applying strip(), mystring has leading and trailing spaces, and the len(mystring) returns the total length of the string including these spaces.
  3. After calling strip(), the extra spaces are removed, and cleanstring contains only the text "python examples". The len(cleanstring) returns the length of the cleaned string without the leading and trailing spaces.

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))

Explanation

  1. The mystring.strip() method removes any leading and trailing whitespace characters from mystring. This includes spaces, tabs, and newline characters. In this case, it removes the newline and tab characters before "python examples" and the newlines after the text.
  2. Before applying strip(), the string mystring has leading and trailing whitespaces, and the len(mystring) returns the total length of the string including the whitespace characters.
  3. After the strip() method is applied, the string cleanstring no longer has leading or trailing whitespace, and the len(cleanstring) gives the length of the cleaned string without the extra spaces.

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.


Python Libraries