Python

How to use Python String Strip Method

Sometimes it is required to remove the first or last or both first and last characters from the string when we work with string data. For example, when it requires storing or verifying any password value then it is essential to remove the space from the starting and end of the password to get the exact password value. ltrim(), rtrim() and trim() methods are used in most of the programming languages to remove space or the particular character from the starting, ending, or both sides. The similar task can be done in Python by using lstrip(), rstrip() and strip() methods. How the strip method can be used in Python in multiple ways is shown in this tutorial.Syntax:

string.strip([chars])

strip method has an optional parameter. When this parameter is omitted then this method will remove space from the starting and ending from string data. But if you want to remove the specific character from the starting and end of the string then you have to set the character as argument value for the method. It returns the main string value after removing the particular characters from the string. Different uses of the strip method in python are shown in the following example.

Example-1: Use of strip method to remove space

The following script shows the use of the strip method without the argument. Here, two variables named username and password are defined. username contains space at the starting of the value and the password contains space at the ending of the value. In the first if statement, the values of the variables are compared without removing the space from the values and it returns false. In the second if statement, strip() method is used with the variables to remove any starting and ending spaces from the values.

#!/usr/bin/env python3

# Define two string values with starting and ending space
username = " admin"
password = " hello123 "

# Compare the strings without removing space
print("Output without strip method:")

if(username == "admin" and password == "hello123"):
  print("Authenticated user\n")
else:
  print("Not Authenticated user\n")

# Compare the strings by removing space
print("Output with strip method:")

if(username.strip() == "admin" and password.strip() == "hello123"):
  print("Authenticated user")
else:
  print("Not Authenticated user")

Output:

The first output is ‘Not Authenticated user’ and the second output is ‘Authenticated user’.

Example-2: Use of strip method to remove the particular character

If you want to delete a specific character from the string value then you have to use the optional argument of the strip method. The following script shows the use of the optional argument of the strip method. A string value will be taken as input and stored in the variable named string1 and a character will be taken as input and stored in the variable named char1. Next, char1 is used as an argument in the strip method. If the value of char1 exists one or multiple times in the string1 at the starting or ending those characters will be removed and store the new value in another variable, newString. The original string will remain unchanged.

#!/usr/bin/env python3

# Take a string data as input
string1 = input("Enter a string\n")
# Take a character data as input
char1 = input("Enter a character to remove from the string\n")

# Remove the character from both side of the string data
newString = string1.strip(char1)

# print the original string
print("The original string is :\n%s" %string1)
# Print the string after stripping
print("The output after removing '%c' from the string is:\n%s" %(char1, newString))

Output:

Run the script. Here, ‘$$$Python is a high-level language$$’ is taken as input string in the output and ‘$’ is as taken as removing a character. strip() method will remove all ‘$’ from the starting and end of the input string.

Example-3: Use of strip to remove multiple characters

The previous two examples remove space or a specific character from a string data. But sometimes you will require to remove multiple characters from the string. The following script shows the way to remove the multiple characters from both sides of a string value. The script will take a URL address and multiple characters from the user as input and store in the variables, url and charList. Here, an infinite loop is used to run the script until the user press, ‘y’ or ‘Y’. In each iteration of the loop, the original string and the new string after stripping will be printed.

#!/usr/bin/env python3

# Define an infinite loop
while(True):
  # Take an url address as input
  url = input("Enter a URL address\n")
  # Take a string data as input
  charList = input("Enter the characters to remove\n")
  '''Remove the character from both side of the string data
     where matches'''

  newString = url.strip(charList)

  # print the original string
  print("The original string is :\n%s" %url)
  # Print the string after stripping
  print("The output after removing the characters\n%s" %newString)

  # ask user to continue the script or not
  answer= input("Do you want to quit(y/n)?")
  # Terminate the loop if the answer is 'y' or 'Y'
  if (answer == 'y' or answer == 'Y'):
    break

Output:

In the output, the loop is iterated two times. In the first iteration, the multiple characters, ‘http://’ will be searched and removed from both sides of the input string, https://www.google.com. Next, ‘n’ is pressed as input to continue the loop and run the script again. In the second iteration, ‘www.com’ characters will be searched and removed from the input string, www.linuxhint.com. Now, ‘y’ is pressed to terminate the infinite loop and exit from the script.

Conclusion:

The usage of the strip method to remove space, single character, and multiple characters from both sides of a string value are shown in the examples of this tutorial. If you want to remove characters from the beginning of the string only then you have to use lstrip() method, and if you want to remove characters from the end of the string only then you have to use rstrip() method.How to use Python String Strip Method

Watch Author’s Video: here

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.