
To replace whitespaces in a Python string with underscores you can use the following command: > message.replace(" ","_") What if you want to replace whitespaces with underscoscores? Note: the replace method returns a copy of the original string considering that Python strings are immutable. > print(message.replace(" ","", 2))Īs you can see the first and second spaces have been replaced with an empty character but the third space has not been replaced. It also provides an optional third argument that allows to specify how many occurrences of the first substring (in this case the space) you want to replace. The replace() method replaces the occurrences of the substring passed as first argument (in this case the space ” “) with the second argument (in this case an empty character “”). Let’s apply this method to the string below: > message = " Welcome to Codefather.tech " The easiest approach to remove all spaces from a string is to use the Python string replace() method.

Spaces, we are coming for you! How to Remove all Spaces from a String in Python We will start with the approach that works in most cases and then look at other options to give you a more complete knowledge of the topic.

An alternative approach is to use a regular expression.

If the spaces to remove are just at the beginning and at the end of the string the strip() method also works fine. The simplest approach is to use the string replace() method. There are multiple ways to remove spaces from a Python string. Are you wondering how to remove spaces from a string in Python? You are in the right place, keep reading, you will know how to do it quickly.
