Home »
Python
Remove leading and trailing spaces from a string using string.strip() function in Python
Python - string.strip() function with Example: In this article, we are going to learn about strip() method in Python, which is used to remove leading and trailing spaces from a given string.
Submitted by IncludeHelp, on January 21, 2018
Python - string.strip() function
strip() is an in-built function in Python and it is used to remove leading and trailing spaces from a string, strip() is called with the string object (variable), does not take any argument generally (one argument is optional which we will discuss in next article) and it returns a copy of string without leading and trailing spaces.
Syntax: string.strip()
Note: There is an optional parameter, which is used to remove particular character/string from the beginning and end of the string.
Example:
Input string: " Hello world "
Output string: "Hello world"
# Python code to remove leading and trailing spaces from a string (An example of string.strip() function)
# Python code to remove leading & trailing spaces
# An example of string.strip() function)
# defining string
str_var = " Hello world "
#printing actual string
print "Actual string is:\n", str_var
# printing string without
# leading & trailing spaces
print "String w/o spaces is:\n", str_var.strip()
Output
Actual string is:
Hello world
String w/o spaces is:
Hello world
It does not remove spaces between the words
In this example, there were spaces before the string and between the words, but function will remove only spaces before the string (Leading spaces), it will not remove spaces between the words. Consider the given example,
# Python code to remove leading & trailing spaces
# An example of string.strip() function)
# defining string
str_var = " Hello world"
#printing actual string
print "Actual string is:\n", str_var
# printing string without
# leading & trailing spaces
print "String w/o spaces is:\n", str_var.strip()
Output
Actual string is:
Hello world
String w/o spaces is:
Hello world