Remove Spaces Before or After a Phrase in Python

Remove Spaces Before or After a Phrase in Python

It has been a while since I last posted, but here is a quick programming tip. You may come across a situation where you want to remove the spaces before or after a phrase. However, you cannot simply replace all spaces, because then the phrase will be mashed together. So, here is a trick to remove only the spaces before or after the word in python.

string = " Welcome to Game 103 "
#This will remove the spaces before 'Welcome'
while string[0] == " ": string = string[1:]
#This will remove the spaces after '103'
while string[-1] == " ": string = string[:-1]

This code simply keeps shortening string until it finds a character that is not a space.

Enjoy the site,
James Grams

Posted in remove blank spots after a string, remove blank spots before a string, remove spaces in python, shortening strings python

Leave a Reply

Your email address will not be published. Required fields are marked *