How do I strip all the spaces in a python string? For example, I want a string like strip my spaces
to be turned into stripmyspaces
, but I cannot s
TL/DR
This solution was tested using Python 3.6
To strip all spaces from a string in Python3 you can use the following function:
def remove_spaces(in_string: str):
return in_string.translate(str.maketrans({' ': ''})
To remove any whitespace characters (' \t\n\r\x0b\x0c') you can use the following function:
import string
def remove_whitespace(in_string: str):
return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))
Explanation
Python's str.translate
method is a built-in class method of str, it takes a table and returns a copy of the string with each character mapped through the passed translation table. Full documentation for str.translate
To create the translation table str.maketrans
is used. This method is another built-in class method of str
. Here we use it with only one parameter, in this case a dictionary, where the keys are the characters to be replaced mapped to values with the characters replacement value. It returns a translation table for use with str.translate
. Full documentation for str.maketrans
The string
module in python contains some common string operations and constants. string.whitespace
is a constant which returns a string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.Full documentation for string
In the second function dict.fromkeys
is used to create a dictionary where the keys are the characters in the string returned by string.whitespace
each with value None
. Full documentation for dict.fromkeys