Remove extra spaces python

Remove Space in Python – (strip Leading, Trailing, Duplicate spaces in string)

Remove space in python string / strip space in python string : In this Tutorial we will learn how to remove or strip leading , trailing and duplicate spaces in python with lstrip() , rstrip() and strip() Function with an example for each . lstrip() and rstrip() function trims the left and right space respectively. strip() function trims all the white space.

  • Remove (strip) space at the start of the string in Python – trim leading space
  • Remove (strip) space at the end of the string in Python – trim trailing space
  • Remove (strip) white spaces from start and end of the string – trim space.
  • Remove all the spaces in python
  • Remove Duplicate Spaces in Python
  • Trim space in python using regular expressions.

Let’s see the example on how to Remove space in python string / strip space in python string one by one.

Remove Space at the start of the string in Python (Strip leading space in python):

## Remove the Starting Spaces in Python string1=" This is Test String to strip leading space" print (string1) print (string1.lstrip())

lstrip() function in the above example strips the leading space so the output will be

‘ This is Test String to strip leading space’

‘This is Test String to strip leading space’

Remove Space at the end of the string in Python (Strip trailing space in python):

## Remove the Trailing or End Spaces in Python string2="This is Test String to strip trailing space " print (string2) print (string2.rstrip())

rstrip() function in the above example strips the trailing space so the output will be

‘This is Test String to strip trailing space ‘

‘This is Test String to strip trailing space’

Remove Space at the Start and end of the string in Python (Strip trailing and trailing space in python):

## Remove the whiteSpaces from Beginning and end of the string in Python string3=" This is Test String to strip leading and trailing space " print (string3) print (string3.strip())

strip() function in the above example strips, both leading and trailing space so the output will be

‘ This is Test String to strip leading and trailing space ‘

Читайте также:  Range тип данных в питоне

‘This is Test String to test leading and trailing space’

Remove or strip all the spaces in python:

## Remove all the spaces in python string4=" This is Test String to test all the spaces " print (string4) print (string4.replace(" ", ""))

The above example removes all the spaces in python. So the output will be

‘ This is Test String to test all the spaces ‘

‘ThisisTestStringtotestallthespaces’

Remove or strip the duplicated space in python:

# Remove the duplicated space in python import re string4=" This is Test String to test duplicate spaces " print (string4) print (re.sub(' +', ' ',string4))
  • We will be using regular expression to remove the unnecessary duplicate spaces in python.
  • sub() function: re.sub() function takes the string4 argument and replaces one or more space with single space as shown above so the output will be.

‘ This is Test String to test duplicate spaces ‘

‘ This is Test String to test duplicate spaces ‘

Using Regular Expression to trim spaces:

re.sub() function takes the string1 argument and apply regular expression to trim the white spaces as shown below

string1 = " This is to test space " print('Remove all space:',re.sub(r"\s+", "", string1), sep='') # trims all white spaces print('Remove leading space:', re.sub(r"^\s+", "", string1), sep='') # trims left space print('Remove trailing spaces:', re.sub(r"\s+$", "", string1), sep='') # trims right space print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", string1), sep='') # trims both

so the resultant output will be


Remove all space:’Thisistotestspace’
Remove leading space:’This is to test space ‘
Remove trailing spaces:’ This is to test space’
Remove leading and trailing spaces:’This is to test space’

Author

With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark. View all posts

Источник

How Do You Remove Spaces From a Python String?

Remove spaces from a string in Python

Are you wondering how to remove spaces from a string in Python? You are in the right place, keep reading, and you will know how to do it quickly.

There are multiple ways to remove spaces from a Python string. The simplest approach is to use the string replace() method. If the spaces to remove are just at the beginning and at the end of the string the strip() method also works fine. An alternative approach is to use a regular expression.

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.

Spaces, we are coming for you!

How to Remove all Spaces from a String in Python

The easiest approach to remove all spaces from a string is to use the Python string replace() method.

Let’s apply this method to the string below:

>>> message = " Welcome to Codefather.tech " >>> print(message.replace(" ","")) WelcometoCodefather.tech 

The replace() method replaces the occurrences of the substring passed as the first argument (in this case the space ” “) with the second argument (in this case an empty character “”).

It also provides an optional third argument that allows specifying how many occurrences of the first substring (in this case the space) you want to replace.

>>> print(message.replace(" ","", 2)) Welcometo Codefather.tech 

As you can see the first and second spaces have been replaced with an empty character but the third space has not been replaced.

Читайте также:  Язык русский php как установить

Note: the replace method returns a copy of the original string considering that Python strings are immutable.

What if you want to replace whitespaces with underscores?

To replace whitespaces in a Python string with underscores you can use the following command:

>>> message.replace(" ","_") '_Welcome_to_Codefather.tech_' 

How to Strip all Whitespaces from a String Using Python

An alternative way to remove whitespaces from a string is to use the split() and join() functions.

Firstly, we apply the split() function to our string:

>>> message.split() ['Welcome', 'to', 'Codefather.tech'] 

…the split() method converts our string into a list of strings and takes away all the whitespaces.

This means that we can then use the string join() method to put the items of the list together.

The join() method has the following syntax:

And here is how you can use it in practice and apply it to an empty string.

>>> "".join(message.split()) 'WelcometoCodefather.tech' 

If you want to keep the spaces between the three words you can use the following instead…

>>> message = " Welcome to Codefather.tech " >>> " ".join(message.split()) 'Welcome to Codefather.tech' 

How to Remove Spaces From the Beginning of a String in Python

What if you only want to remove spaces from the beginning of a string?

Let’s say we have the following string…

To remove leading spaces you can use the string lstrip() method.

This method will not remove any trailing spaces.

Remove Trailing Spaces from a Python String

To remove trailing spaces from a string Python provides the rstrip() string method.

>>> message = " Hello " >>> print(message.rstrip()) Hello 

Ok, we can see that the leading spaces have not been removed. But it’s a bit tricky to confirm that the trailing spaces have actually been removed considering that we cannot see them.

Let’s try something to confirm they have been removed.

>>> print(len(message)) 12 >>> print(len(message.rstrip())) 9 

By using the len() function we can confirm that three characters (the trailing spaces) have been removed from the string.

Remove Spaces from the Beginning and End of a String in Python

In the previous two sections, we have seen that Python provides two string methods to remove spaces from the beginning and the end of a string.

What if we want to remove spaces both at the start and the end of a string with a single line of code?

To remove spaces from the beginning and the end of a string you can use the string strip() method.

>>> message = " Hello " >>> print(message.strip()) Hello >>> print(len(message.strip())) 5 

The string returned by the strip() method has only 5 characters because spaces both at the beginning and at the end of the string have been removed.

In theory, you could also apply the lstrip() and rstrip() methods in a single line of code and achieve the same result.

>>> print(message.lstrip().rstrip()) Hello >>> print(len(message.lstrip().rstrip())) 5 

Notice how Python allows the application of two methods in a single line of code using the dot notation.

You now know how to remove spaces from both ends of a string.

How to Remove Extra Spaces Between Words from a String with Python

There might be a scenario where you don’t want to replace all the spaces in a string, you just want to remove some extra spaces.

Читайте также:  Тег COL, атрибут span

For example, let’s say you want to replace two consecutive spaces (where present) with a single space.

>>> message = "Hello from Codefather" 

Between the three words, there are two spaces and I want to replace them with one. To do that we can use the replace() method.

>>> print(message.replace(" ", " ")) Hello from Codefather 

We pass the two consecutive spaces as the first argument (” “) and a single space as the second argument (” “).

Using Python Regular Expressions to Remove Spaces from a String

Let’s analyze a different approach to remove spaces from a string: we will use Python regular expressions.

Regular expressions are one of these topics many developers avoid especially at the beginning of their coding career.

…regular expressions are very powerful and it’s a good practice to use them often in order to become more and more used to them.

The module to handle regular expressions in Python is called re. To remove spaces from a Python string we will use the re.sub() function.

Here is the syntax of the re.sub() function:

re.sub(pattern_to_be_replaced, replacement_pattern, string)
>>> message = "Hello from Codefather" >>> re.sub("\s", "", message) Traceback (most recent call last): File "", line 1, in NameError: name 're' is not defined 

It’s caused by the fact that we haven’t imported the re module first.

>>> import re >>> re.sub("\s+", "", message) 'HellofromCodefather' 

Let’s look at the pattern to be replaced considering that the other two arguments are pretty straightforward.

The pattern \s+ applied to a Python regular expression matches whitespace characters (including [ \t\n\r\f\v]). If you replace the lowercase s with a capital s (“\S+”) the pattern matches any non-whitespace characters.

Using a Regular Expression to Replace Spaces at the Beginning of a String

A regular expression can also be used to replace spaces at the beginning of a string by adding an extra character to the pattern we have used before.

>>> re.sub("^\s+", "", message) 'Hello from Codefather ' 

We have added the ^ character at the beginning of the pattern to refer to the beginning of the line.

The result is the same as you get with the lstrip() method.

>>> message.lstrip() 'Hello from Codefather ' 

Using a Regular Expression to Replace Spaces at the End of a String

We can use regular expression as an alternative to the rstrip() method to remove trailing spaces from a string.

Let’s see what else we have to add to the regular expression pattern to make it happen.

>>> re.sub("\s+$", "", message) ' Hello from Codefather' 

Adding the $ at the end of the “\s+” pattern allows matching only the whitespaces at the end of the string.

The result is the same as the rstrip() method…

>>> message.rstrip() ' Hello from Codefather' 

Conclusion

You now have enough ways to replace or remove white spaces in Python strings.

Just pick the one you prefer and that also fits the specific scenario you are dealing with.

Bonus read: in this tutorial, you have learned how to remove spaces from strings in Python. To complement this knowledge have a look at how to concatenate strings in Python. It will help you with your Python programs!

Related course: build a strong Python foundation with this Python specialization.

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Источник

Оцените статью