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.
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
- The
strip()
method removes all leading and trailing whitespace characters frommystring
, which in this case includes spaces before and after the string "python examples". - Before applying
strip()
,mystring
has leading and trailing spaces, and thelen(mystring)
returns the total length of the string including these spaces. - After calling
strip()
, the extra spaces are removed, andcleanstring
contains only the text "python examples". Thelen(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
- The
mystring.strip()
method removes any leading and trailing whitespace characters frommystring
. 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. - Before applying
strip()
, the stringmystring
has leading and trailing whitespaces, and thelen(mystring)
returns the total length of the string including the whitespace characters. - After the
strip()
method is applied, the stringcleanstring
no longer has leading or trailing whitespace, and thelen(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.