Remove space in string python

I want to eliminate all the whitespace from a string, on both ends, and in between words.

I have this Python code:

def my_handle(self):
    sentence = ' hello  apple  '
    sentence.strip()

But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?

asked Nov 25, 2011 at 13:51

Remove space in string python

0x120x12

18.2k21 gold badges65 silver badges123 bronze badges

3

If you want to remove leading and ending spaces, use str.strip():

>>> "  hello  apple  ".strip()
'hello  apple'

If you want to remove all space characters, use str.replace() (NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace):

>>> "  hello  apple  ".replace(" ", "")
'helloapple'

If you want to remove duplicated spaces, use str.split() followed by str.join():

>>> " ".join("  hello  apple  ".split())
'hello apple'

Remove space in string python

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Nov 25, 2011 at 13:56

Cédric JulienCédric Julien

76.1k15 gold badges121 silver badges128 bronze badges

7

To remove only spaces use str.replace:

sentence = sentence.replace(' ', '')

To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:

sentence = ''.join(sentence.split())

or a regular expression:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

If you want to only remove whitespace from the beginning and end you can use strip:

sentence = sentence.strip()

You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.

Randall Cook

6,5986 gold badges32 silver badges67 bronze badges

answered Nov 25, 2011 at 13:54

Mark ByersMark Byers

781k184 gold badges1551 silver badges1440 bronze badges

2

An alternative is to use regular expressions and match these strange white-space characters too. Here are some examples:

Remove ALL spaces in a string, even between words:

import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)

Remove spaces in the BEGINNING of a string:

import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)

Remove spaces in the END of a string:

import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)

Remove spaces both in the BEGINNING and in the END of a string:

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)

Remove ONLY DUPLICATE spaces:

import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))

(All examples work in both Python 2 and Python 3)

answered Feb 19, 2015 at 13:05

Emil StenströmEmil Stenström

12.3k8 gold badges49 silver badges73 bronze badges

3

"Whitespace" includes space, tabs, and CRLF. So an elegant and one-liner string function we can use is str.translate:

Python 3

' hello  apple '.translate(str.maketrans('', '', ' \n\t\r'))

OR if you want to be thorough:

import string
' hello  apple'.translate(str.maketrans('', '', string.whitespace))

Python 2

' hello  apple'.translate(None, ' \n\t\r')

OR if you want to be thorough:

import string
' hello  apple'.translate(None, string.whitespace)

Remove space in string python

ib.

26.7k10 gold badges77 silver badges99 bronze badges

answered Nov 28, 2015 at 3:36

Remove space in string python

MaKMaK

1,6081 gold badge16 silver badges6 bronze badges

3

For removing whitespace from beginning and end, use strip.

>> "  foo bar   ".strip()
"foo bar"

answered Nov 25, 2011 at 13:56

wal-o-matwal-o-mat

6,9487 gold badges30 silver badges40 bronze badges

2

' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})

MaK already pointed out the "translate" method above. And this variation works with Python 3 (see this Q&A).

Remove space in string python

Asclepius

52k15 gold badges150 silver badges131 bronze badges

answered Sep 26, 2016 at 9:54

Remove space in string python

1

In addition, strip has some variations:

Remove spaces in the BEGINNING and END of a string:

sentence= sentence.strip()

Remove spaces in the BEGINNING of a string:

sentence = sentence.lstrip()

Remove spaces in the END of a string:

sentence= sentence.rstrip()

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:

" 1. Step 1\n".strip(" ")

Or you could remove extra commas when reading in a string list:

"1,2,3,".strip(",")

answered Apr 6, 2018 at 20:51

Remove space in string python

cacti5cacti5

1,8002 gold badges24 silver badges32 bronze badges

Be careful:

strip does a rstrip and lstrip (removes leading and trailing spaces, tabs, returns and form feeds, but it does not remove them in the middle of the string).

If you only replace spaces and tabs you can end up with hidden CRLFs that appear to match what you are looking for, but are not the same.

Remove space in string python

answered Nov 12, 2014 at 19:30

yan bellavanceyan bellavance

4,58020 gold badges59 silver badges92 bronze badges

1

answered Mar 13, 2020 at 15:51

Remove space in string python

handlehandle

6,1443 gold badges49 silver badges76 bronze badges

1

I use split() to ignore all whitespaces and use join() to concatenate strings.

sentence = ''.join(' hello  apple  '.split())
print(sentence) #=> 'helloapple'

I prefer this approach because it is only a expression (not a statement).
It is easy to use and it can use without binding to a variable.

print(''.join(' hello  apple  '.split())) # no need to binding to a variable

answered Jul 29, 2021 at 14:33

naoki fujitanaoki fujita

6611 gold badge7 silver badges13 bronze badges

import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)

answered Oct 24, 2016 at 12:46

Remove space in string python

1

In the following script we import the regular expression module which we use to substitute one space or more with a single space. This ensures that the inner extra spaces are removed. Then we use strip() function to remove leading and trailing spaces.

# Import regular expression module
import re

# Initialize string
a = "     foo      bar   "

# First replace any number of spaces with a single space
a = re.sub(' +', ' ', a)

# Then strip any leading and trailing spaces.
a = a.strip()

# Show results
print(a)

answered Feb 19 at 10:59

Remove space in string python

2

I found that this works the best for me:

test_string = '  test   a   s   test '
string_list = [s.strip() for s in str(test_string).split()]
final_string = ' '.join(string_array)
# final_string: 'test a s test'

It removes any whitespaces, tabs, etc.

answered Jul 25 at 10:08

try this.. instead of using re i think using split with strip is much better

def my_handle(self):
    sentence = ' hello  apple  '
    ' '.join(x.strip() for x in sentence.split())
#hello apple
    ''.join(x.strip() for x in sentence.split())
#helloapple

answered Oct 10, 2020 at 19:36

Remove space in string python

Assad AliAssad Ali

2791 silver badge12 bronze badges