Python strip() with example

We’ll study a Python String strip() function in this tutorial with the aid of examples.

Python String strip() Method

The string’s leading and trailing characters are eliminated using the strip() function to produce a string duplicate (depending on the given string parameter).

Syntax:

string.strip([chars])
ParameterDescription
chars characters to remove as leading/trailing characters

 

Note: The string is stripped of all leading and following whitespaces if the chars parameter is not given.

Python Code will be:

character = '     Amandeep Singh  '

# eliminate leading and trailing whitespaces
print('Output:', character.strip())

The output will be:

Output: Amandeep Singh

A duplicate of the string that has both the beginning and ending characters removed is what strip() delivers.

How the strip() function operates

It stops eliminating the leading characters after a character in the string on the left matches every character in the chars parameter.
Similar to this, it stops eliminating trailing characters whenever the text of the string on the right does not match any of the words in the chars parameter.

Another Python example of strip() function to understand in an easy manner:

word = '  abc aabbcc bbccdd   '

# Leading and trailing whitespaces are eliminated
print(word.strip())

# All whitespace,a,b,c characters in the left and right of string are removed
print(word.strip(' abc'))

# Argument doesn't contain space so no characters are removed.
print(word.strip('am'))

word2 = 'Welcome to Code Speedy'
print(word2.strip('We'))

word3 = ",,,,,aman.....deep....singh"

a = word3.strip(",.aman")

print(a)

The output will be:

abc aabbcc bbccdd
dd
  abc aabbcc bbccdd   
lcome to Code Speedy
deep....singh
>

I hope you like this article.

Also read: Remove whitespace from the start and end of a string in Python

Leave a Reply

Your email address will not be published. Required fields are marked *