Skip to content
Home » Stripping Strings in Python

Stripping Strings in Python

Spread the love

Today we’ll be talking about stripping strings. In two of my previous articles we were talking about joining and splitting strings. If you want to read them, here they are:

1) joining strings

2) splitting strings

In this article we’ll be talking about three other string methods, which are used to strip strings. They all work in a similar way. The methods used for stripping strings are strip, rstrip and lstrip.

We’ll learn how to remove whitespace characters on the left, on the right and on both sides simultaneously.

The method lstrip removes all leading whitespace characters in a string. Alternatively we can use it with an argument representing the characters which should be trimmed on the left:

>>> "         and so they did.".lstrip()
'and so they did.'

>>> "***** stars *****".lstrip("*")
' stars *****'

The method rstrip removes all trailing whitespace characters in a string. Again, we can alternatively pass an argument representing the characters which should be trimmed on the right:

>>> "What ?    ".rstrip()
'What ?'

>>> "######## NO ########".rstrip("#")
'######## NO '

We can use the strip method to combine lstrip and rstrip and trim the string on both sides:

>>> text = "******************WATCH IT*********"
>>> text.strip("*")
'WATCH IT'

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply