Home » Python

Remove leading and trailing characters/string from a string using string.strip(char) function in Python

Python - string.strip(char) function with Example: In this article, we are going to learn about strip(char) method in Python, which is used to remove leading and trailing characters/string from a given string.
Submitted by IncludeHelp, on January 21, 2018

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! 



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.