remove all whitespaces from string in python

You can remove all whitespaces from a string in Python using either string's replace method or regular expressions in the re module.

Using replace method:

main.py
string_with_spaces = "this string has spaces"
no_spaces_string = string_with_spaces.replace(" ", "")
print(no_spaces_string)  # output: "thisstringhasspaces"
158 chars
4 lines

Using re module:

main.py
import re

string_with_spaces = "this string has spaces"
no_spaces_string = re.sub(r"\s+", "", string_with_spaces)
print(no_spaces_string)  # output: "thisstringhasspaces"
172 chars
6 lines

In the second example, r"\s+" is a regular expression that matches one or more whitespace characters. sub method replaces all matches of this pattern with an empty string, effectively removing all whitespaces.

gistlibby LogSnag