w Python: Remove all whitespaces from a string - w3resource
w3resource

Python: Remove all whitespaces from a string


40. Remove All Whitespace

Write a Python program to remove all whitespaces from a string.

Sample Solution:-

Python Code:

import re
text1 = ' Python    Exercises '
print("Original string:",text1)
print("Without extra spaces:",re.sub(r'\s+', '',text1))

Sample Output:

Original string: Python    Exercises                                                                            
Without extra spaces: PythonExercises 

Pictorial Presentation:

Python: Regular Expression - Remove all whitespaces from a string.

Flowchart:

Flowchart: Regular Expression - Remove all whitespaces from a string.

For more Practice: Solve these Related Problems:

  • Write a Python program to remove all whitespace characters from a string.
  • Write a Python script to strip all spaces, tabs, and newline characters from a given text.
  • Write a Python program to delete every whitespace in a string and then output the condensed result.
  • Write a Python program to process a text and return the version with no whitespace at all.

Go to:


Previous: Write a Python program to remove multiple spaces in a string.
Next: Write a Python program to remove everything except alphanumeric characters from a string.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.