Python Strip Function – strip() [With Examples]

Introduction to Python Strip Function

The Python strip() function is one of the Python library’s built-in functions. The strip() method eliminates characters from the beginning and end of a string. Strip() removes white spaces from the beginning and end of a string by default and returns the same string without them.

parameters (optional):

  • The characters specify will be append to the beginning or end of the existing string.
  • The whitespaces at the beginning and end of the string will be eliminate if the character’s parameter is not specified.

Return Value:

  • If the characters to be remove are not given. The Python String strip() function will return the original string with white spaces remove from the start and end.
  • There are no whitespaces at the beginning or end of the string, it will be return unchange and will match the original string.
  • If the character’s argument is set to match. The characters at the beginning and end of the string will be remove from the original string and the rest of the string will be return.
  • If the characters pass does not match the beginning or end of the original string, the string will be return unchange.

Syntax and Code Examples

Syntax:

string.strip([chars])

Parameter: There is only one optional parameter in it.

  • chars – a string indicating which characters should be eliminate. If the optional chars parameter is omit. The string is strip of all preceding and trailing whitespaces.

Return Value: A string that specifies which characters should be remove. The string is stripped of all preceding and trailing whitespaces if the optional chars parameter is omitted.

Let’s have a look at some examples.

Example 01:

string = "softhunt.net"

print(string)

print(string.strip())

print(string.strip('softhunt'))

Output:

img1

Example 02:

name = 'softhunt.net'
print(name)

strip_string = 'net'

print(name.strip(strip_string))

Output:

img2

Working of the above code:

To begin, create a string name = ‘softhunt.net’. Now we run the strip method on str1 and supply the argument strip_string = ‘net’. From now on, The python interpreter is now tracing names from the left. If a character from the name is present in strip_string, it is remove. Otherwise, the tracing will come to a halt. Finally, the generated string is returned. Strip() removes leading and following spaces when called without an argument.

Example 03:

name = " softhunt.net "

print(name)

print(name.strip())

Output:

img3

That’s all for this article. If you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. Python Function vs Method
  2. Understanding Permutations Python Function [With Examples]
  3. floor() and ceil() function in python

Leave a Comment