Strip from a String in Python

Python Strip From String

Let’s take a look at how we can strip from a string in Python.

Python provides us with different ways to remove trailing characters like newlines, spaces, and tabs from a Python String. This is called stripping from a String.


How to Strip from a String in Python

We can use any of the below methods to strip from a String:

  • strip() – This strips both leading and trailing white-spaces (” “), tabs (“\t”) and newlines (“\n”) as well, and returns the trimmed string.
  • rstrip() – This strips any trailing white-spaces, tabs, and newlines, and returns the trimmed string. Since we only trim on the right, this is aptly called rstrip().
  • lstrip() – We only trim leading characters and return the trimmed string. Since this only trims leftmost characters, this is called lstrip().

There are string methods, so we call them on the String object. They don’t take any arguments, so the syntax for calling them will be:

# Strip from both left and right
my_string.strip()

# Strip only from the right
my_string.rstrip()

# Strip only from the left
my_string.lstrip()

Let’s take an example to visualize this: (We place an end of string marker called “_ENDOFSTRING” to see whether the trailing spaces and tabs are removed or not.

my_string = "\t  Hello from JournalDev\t   \n"

print("Original String (with tabs, spaces, and newline)", my_string + "_ENDOFSTRING")

print("After stripping leading characters using lstrip(), string:", my_string.lstrip() + "_ENDOFSTRING")

print("After stripping trailing characters using rstrip(), string:", my_string.rstrip() + "_ENDOFSTRING")

print("After stripping both leading and trailing characters using strip(), string:", my_string.strip() + "_ENDOFSTRING")

Output

Original String (with tabs, spaces, and newline)          Hello from JournalDev    
_ENDOFSTRING
After stripping leading characters using lstrip(), string: Hello from JournalDev           
_ENDOFSTRING
After stripping trailing characters using rstrip(), string:       Hello from JournalDev_ENDOFSTRING
After stripping both leading and trailing characters using strip(), string: Hello from JournalDev_ENDOFSTRING

Notice that in the case of lstrip(), the trailing characters (along with the newline) are still present, while they are removed in rstrip() and strip().


Conclusion

In this article, we learned how we could use various methods to strip from a String in Python.


References

  • JournalDev article on trimming a String