Trim off white space characters in Python

Trim off white space characters in Python

Having a space at the beginning or the end of a string can be frustrating when formatting output. Even more so if the string came from user input and really shouldn't have spaces surrounding the information, like a name or an address.

Here's how we can quickly get rid of that:

input_string = " Mauricio De La Cruz "
# OUTPUT: print(input_string)
#  Mauricio De La Cruz 

clean_string = input_string.strip()
# OUTPUT: print(clean_string)
# Mauricio De La Cruz

Notice how it maintained the spaces in the middle of the string—which is exactly what we want to keep. However, the spaces around the name have been removed, making it so much easier to work with.

Using strip()

My most common use case would be to use this as part of a chain of text transformations. For example, if I needed to turn a title into a slug for a URL.

title = "Some Title "
...

slug = title.lower().strip().replace(" ", "-")
# OUTPUT: print(slug)
# some-title

Since a URL is pretty important to get right, we want to double-check that the spaces have been removed from the title (which will contain random, user-input). We also want the strip method to come before we replace all of the spaces with hyphens, lest our slug look like this:
/some-title-/

String Cleaning ;)

There you have it—a quick and efficient way to tidy up your text with Python's strip() method. Whether you're handling user input or preparing text for a URL, this built-in string method can save you from the hassle of dealing with unwanted spaces.