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
Alternatively,
"strip my spaces".translate( None, string.whitespace )
And here is Python3 version:
"strip my spaces".translate(str.maketrans('', '', string.whitespace))
import re
re.sub(' ','','strip my spaces')
If optimal performance is not a requirement and you just want something dead simple, you can define a basic function to test each character using the string class's built in "isspace" method:
def remove_space(input_string):
no_white_space = ''
for c in input_string:
if not c.isspace():
no_white_space += c
return no_white_space
Building the no_white_space
string this way will not have ideal performance, but the solution is easy to understand.
>>> remove_space('strip my spaces')
'stripmyspaces'
If you don't want to define a function, you can convert this into something vaguely similar with list comprehension. Borrowing from the top answer's join
solution:
>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'
Taking advantage of str.split's behavior with no sep parameter:
>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
If you just want to remove spaces instead of all whitespace:
>>> s.replace(" ", "")
'\tfoo\nbar'
Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:
$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop
Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:
$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop
Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.
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