White Space in Python

In a previous lesson, you may have noticed that if you enter Jessica Jones or Luke Cage with two spaces in the middle, you'll still be left with one of them. There are three inbuilt functions in Python that can help you trim white space from text.

The Python strip function

The strip() function in Python strips white space from the left and right of your string. You use it like this:

stripAllWhitespace = sName.strip()

At its simplest, you can use the strip() function with an empty pair of round brackets. Notice, though, that you would have to create a new variable for your stripped string. This is because strings are immutable in Python. You can't change the original string, so you set up a new variable to store the string stripped of its whitespace.

You can also use strip to remove any text you don't want. Suppose your original string was this:

fullName = "Jessica Jones Jessica"

To get rid of the two Jessica's in the string, just type what you want to get rid of between the round brackets of strip:

newname = fullName.strip("Jessica")

The result of this would be the name Jones in the output window. Strangely, this is not stripped of whitespace. So you'd have to use strip again, set up a new variable and strip it of whitespace.

The strip() function not only strips spaces but anything else considered whitespace, such as newline characters, tabs or hard returns.

 

The lstrip and rstrip Python functions

If you only want to strip whitespace from the left or from the right you can use lstrip() or rstrip():

myText = "       Some space needs trimming from the left."
stripLeft = myText.lstrip()

myText = "Some space needs trimming from the right.       "
stripLeft = myText.rstrip()

We'll move on for the next section and have a look at lists in Python.

Python Lists >