In Python, the str.strip() method is used to remove leading and trailing whitespaces from a string. By default, the strip() method removes any whitespace characters from the beginning and end of the string, such as spaces, tabs, and newlines.
The strip() function is a string method that removes leading and trailing whitespace characters from a string. By default, it removes spaces, tabs, and newline characters from the beginning and end of a string.
However, it can also be used to remove any specified characters from the beginning and end of a string.
Here's an example of strip() method:
It's important to note that the strip() function returns a new string and does not modify the original string.
We can also use lstrip() and rstrip() to remove leading and trailing whitespaces respectively.
strip() function in Python is a useful method for removing unwanted characters from the beginning and end of a string, which helps in cleaning up the data and making it ready for further processing or analysis.
original_string = " Hello World "
stripped_string = original_string.strip()
print(stripped_string)
This will print "Hello World" with leading and trailing whitespaces removed.
In addition to removing whitespaces, the strip() method can also remove specific characters from the beginning and end of the string. You can pass one or more characters as arguments to the strip() method, and it will remove those characters from the beginning and end of the string. Here's an example:
original_string = "!!Hello World!!"
stripped_string = original_string.strip('!')
print(stripped_string)
This will print "Hello World" with the leading and trailing '!' characters removed.
Alternatively, you can use lstrip() and rstrip() method to remove leading and trailing whitespaces respectively.
original_string = " Hello World "
stripped_string = original_string.lstrip()
print(stripped_string)
This will print "Hello World " with leading whitespaces removed.
original_string = " Hello World "
stripped_string = original_string.rstrip()
print(stripped_string)
This will print " Hello World" with trailing whitespaces removed.
It's worth noting that, the strip() method returns a new string with the leading and trailing whitespaces removed, it does not modify the original string.