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

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.