Like any other programming language, Python also has a string function strip() to trim a given string. The advantage of using strip is that it can trim white space and also any particular characters if needed.

Example – Python Strip

In the below example we are using strip function without any arguments. It will strip the trailing and leading spaces in the string. The actual string remains the same and the strip() function performs its actions on a copy.

mystr = ' Example Stringgg '
print(mystr.strip())

Now, let us see how to use the strip() function to trim specific characters from a given string. Consider the below example where we are removing the letter ‘g’ from the string.

mystr = 'Example Stringgg'
print(mystr.strip('g'))

Output

Example Strin
Python Strip
Tagged on: