strip() method in python
The strip() function returns a copy of the string with the characters removed from the beginning and end of the string. (From the right and the left). Depending on the character argument being passed.
How to formulate it like this:
string. strip("chars")
chars: [Optional] A set of characters to remove. By default, it removes white spaces from the beginning and end of the string.
Return value: Returns a new string with characters removed from the beginning and end of the string.
If the string contains whitespace and no specific character is provided within the chars argument, the string is returned with whitespace removed by default.
Example:
string = " learn python with ahmed obaid "
# prints the string without stripping
print(string)
# prints the string by removing leading and trailing whitespaces
print(string.strip()
The output will be:
learn python with ahmed obaid
learn python with ahmed obaid
If the string does not contain white spaces and a delimiter character is not provided inside chars argument, the string will be returned as is.
Example:
string = "ahmedobaid.com"
print (string.strip())
The output will be:
ahmedobaid.com
In the following example we will remove the character specified in the chars argument.
Example:
string = "xxxxxxxlearn python with ahmed obaidxxxxxxxx"
print (string.strip("x"))
The output will be:
learn python with ahmed obaid
The strip() function is case sensitive. When we pass a specific character inside the chars argument, the same character with different cases (capital and small) will not be removed.
Example:
string = "xxxxxXXXXXlearn python with ahmed obaidXXXXXxxxxx"
print (string.strip("x"))
The output will be:
XXXXXlearn python with ahmed obaidXXXXX
External sources:
Built-in functions - official Python documentation
If you have any questions or concerns, leave them in the comments
Tags
Python Python String string methods python python string strip
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment