Python remove all double spaces

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 ‘

Читайте также:  Как переслать html страницу

‘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

Источник

Python – Remove Multiple Spaces From a String

In this tutorial, we will look at how to remove multiple spaces from a string in Python such that there is consistent spacing.

How do you remove multiple spaces in a string?

remove multiple spaces from string

You can use regular expressions to match consecutive space characters in the string and replace them with a single space. The following is the syntax –

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# replace multiple spaces with a single space s = re.sub(' +', ' ', s)
import re # string with multiple consecutive spaces s = "I am a doctor" # make spaces consistent s = re.sub(" +", " ", s) print(s)

Multiple spaces were replaced with a single space. Here, the regular expression ‘ +’ matches with occurrences of consecutive spaces which are then replaced by a single space character, ‘ ‘ using the re.sub() function.

Читайте также:  Create blog post html

The regular expression ‘ +’ matches for one or more consecutive occurrences of a single space ‘ ‘ .

Using sting split() and join()

You can also use the string split() and join() functions to remove multiple spaces from a string.

We first split the string using the string split() function and then join the words back with a single space between them using the string join() function. For example –

# string with multiple consecutive spaces s = "I am a doctor" # make spaces consistent s = " ".join(s.split()) print(s)

We get the same result as above.

Note that the string split() function splits the string at whitespace characters by default. Now, whitespace characters are not just limited to a single space in Python. Characters such as ‘\n’ , ‘\t’ , ‘\r’ etc. are also considered whitespace characters in Python.

If you use this method on a string with such characters, they will all be replaced by a single space. For example –

# string with multiple consecutive spaces s = "I am a doctor.\nHe is a scientist." # make spaces consistent s = " ".join(s.split()) print(s)
I am a doctor. He is a scientist.

You can see that multiple spaces were removed from the string. Also, notice that the newline character ‘\n’ was also removed.

Now, let’s use the regular expression method on the same string.

# string with multiple consecutive spaces s = "I am a doctor.\nHe is a scientist." # make spaces consistent s = re.sub(" +", " ", s) print(s)
I am a doctor. He is a scientist.

Only consecutive spaces were replaced by a single space and the newline character was unchanged.

So, be mindful of this when using string split() and join() functions to remove multiple spaces from a string in Python.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Remove duplicate spaces from string in Python

In this article, we will discuss different ways to delete duplicate spaces from a string in Python.

Table Of Contents

Suppose we have a string that contains some duplicate whitespaces,

After removing duplicate whitespaces from it, the final string should be like,

There are different ways to do this. Let’s discuss them one by one,

Frequently Asked:

Remove duplicate spaces from string using split() and join()

In Python, the string class provides a member function split(sep). it splits the string based on the given sep as the delimiter and returns a list of the words. By default it uses the whitespace character as delimeter and discard empty strings.

Читайте также:  Градации серого цвета html

We can split the string into a list of words and then join back those words using single space as delimeter.

For example,

strValue = "This is a simple string" # Remove all duplicate spaces in string strValue = ' '.join( strValue.split() ) print(strValue)

It removed all duplicate spaces from string in Python.

Remove duplicate spaces from string using Regex

In Python, the regex module provides a function to replace the contents of a string based on a matching regex pattern. The signature of function is like this,

sub(pattern, replacement_str, original_str)

It looks for the matches of the given regex pattern in the sting original_str and replaces all occurrences of matches with the string replacement_str.

A regex pattern “\s+” will match all the whitespaces in string. We can replace them by a single space character. This way we can replace duplicate spaces with single space.

For example,

import re strValue = "This is a simple string" # Regex pattern to match all whitespaces in string pattern = "\s+" # Remove all duplicate spaces in string strValue = re.sub(pattern, ' ', strValue ) print(strValue)

It removed all duplicate spaces from string in Python.

We learned about two different ways to delete duplicate spaces from a string in Python.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

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