Home »
Python
Python String strip() Method
By IncludeHelp Last updated : December 08, 2024
Prerequisite: Python - string.strip() function
In the last article, we have discussed how string.strip() removes leading and trailing spaces, here we are discussing how it can be used to remove leading and trailing characters/string from the string?
Syntax: string.strip([char])
[char] is an optional parameter, which specifies particular character or set of characters to remove from beginning and end of the string.
Example:
Input string: "#@# Hello world! #@#"
chars to remove: "#@#"
Output string: " Hello world! "
Python code to remove leading and trailing character or set of characters from the string
# Python code to remove leading & trailing chars
# An example of string.strip(char) function)
# defining string
str_var = "#@# Hello world! #@#"
#printing actual string
print "Actual string is:\n", str_var
# printing string without
# leading & trailing chars
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 characters between the words
In this example, there were "#@#" before, after the string and between the words, but function will remove only "#@#" before the string (Leading), after the string (Trailing), it will not remove "#@#" between the words. Consider the given example,
# Python code to remove leading & trailing chars
# An example of string.strip(char) function)
# defining string
str_var = "#@# Hello #@# world! #@#"
#printing actual string
print "Actual string is:\n", str_var
# printing string without
# leading & trailing chars
print "String w/o spaces is:\n", str_var.strip('#@#')
Output
Actual string is:
#@# Hello #@# world! #@#
String w/o spaces is:
Hello #@# world!