Remove all whitespace in a string in Python

+1 vote

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?

Aug 28, 2018 in Python by bug_seeker
• 15,360 points
2,554 views

2 answers to this question.

0 votes

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

sentence = ' hello apple'
sentence.strip()
>>> 'hello apple'

If you want to remove all spaces, use str.replace():

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

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

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

answered Aug 28, 2018 by Priyaj
• 56,940 points
0 votes

You can also use regular expressions for this.

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)
answered Aug 31, 2018 by Omkar
• 67,660 points

Related Questions In Python

0 votes
1 answer

How to remove all characters before a specific character in Python?

Use re.sub. Just match all the chars ...READ MORE

answered Feb 27 in Python by SDeb
• 13,190 points
907 views
0 votes
1 answer

Looping over a string in python

for c in "string": ...READ MORE

answered May 28, 2018 in Python by Nietzsche's daemon
• 4,260 points
33 views
0 votes
2 answers

Finding the index of a character in python string

You can use word.find('o') as well to ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
124 views
0 votes
1 answer

How to print first character of each word in upper case of a string in Python

You can use split() using space as ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
2,447 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 346 views
+4 votes
6 answers
0 votes
1 answer

Reverse a string in Python

How about: >>> 'hello world'[::-1] 'dlrow olleh' This is ...READ MORE

answered Aug 1, 2018 in Python by Priyaj
• 56,940 points
54 views
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29 in Python by rajesh
• 1,210 points
106 views