Python strip

Python strip string function removes the specified characters from both the Right-hand side and Left-hand side of a string (by default, White spaces) and this method returns a copy of the string as new.

The Python strip function is the combination of rstrip and lstrip, and it removes the leading and trailing whitespaces. Let us see the syntax of the Python strip string function is

  • String_Value: A valid argument.
  • Chars: This parameter is optional. If it omitted, the strip Function considers the white spaces as a default parameter. So, this method removes the leading and trailing spaces. To change the default value, Please specify the trailing and leading characters to remove from a string.

Python strip function Example

The following set of examples helps to know the Python strip Function.

Within this String method example, First, we declared the String variable Str1 and assigned a string with empty spaces on both sides.

  • The first statement removes the white spaces from both the Left & Right-hand side of variable Str1 using Python Strip function and prints the output.
  • From the next two statement output, you can observe that the String strip function returns the output in a new, instead of altering the original.
  • In the next line, we assigned the result to itself for changing the original in Python

As we said earlier, the Python strip function allows using parameters. Within the next two statements, we have zeros on both sides, and we are passing ‘0’ as the argument, which means it removes zeros from both sides. Next, we used two characters to remove (+ and *)

str5 code block is removing only the lead characters or left-hand side of a given sentence using this method (Acting like lstrip).

The last two statements was stripping only the Right-hand side or trailing characters of the string (Acting like rstrip method). Please refer to Python rstrip and Python lstrip function articles.

Str1 = '  Tutorial Gateway  ';

Str2 = Str1.strip()
print('Stripping White spaces using Strip() is =', Str2)

# Observe the Original
print('Converted String is =', Str1.strip())
print('Original String is =', Str1)

# Performing function directly
Str3 = '00000000Tutorial Gateway00000000'.strip('0')
print("Stripping 0's using Strip() is =", Str3)

Str4 = '+++++Tutorial Gateway****'.strip('+*')
print('Stripping + and * on both sides using Strip() is =', Str4)

# Left Side
Str5 = '***********Tutorial Gateway'.strip('*')
print('Stripping Left Side using Strip() is =', Str5)

# Right Side
Str6 = 'Tutorial Gateway========='.strip('=')
print('Stripping Right Side using Strip() is =', Str6)
Python Strip