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 seem to accomplish that with strip():
>>> 'strip my spaces'.strip()
'strip my spaces'
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 seem to accomplish that with strip():
>>> 'strip my spaces'.strip()
'strip my spaces'
string1 = " This is Test String to strip leading space"
print(string1)
print(string1.lstrip())
string2 = "This is Test String to strip trailing space "
print(string2)
print(string2.rstrip())
string3 = " This is Test String to strip leading and trailing space "
print(string3)
print(string3.strip())
string4 = " This is Test String to test all the spaces "
print(string4)
print(string4.replace(" ", ""))
As mentioned by Roger Pate following code worked for me:
s = " \t foo \n bar "
"".join(s.split())
'foobar'
I am using Jupyter Notebook to run following code:
i=0
ProductList=[]
while i < len(new_list):
temp='' # new_list[i]=temp=' Plain Utthapam '
#temp=new_list[i].strip() #if we want o/p as: 'Plain Utthapam'
temp="".join(new_list[i].split()) #o/p: 'PlainUtthapam'
temp=temp.upper() #o/p:'PLAINUTTHAPAM'
ProductList.append(temp)
i=i+2
The standard techniques to filter a list apply, although they are not as efficient as the split/join or translate methods.
We need a set of whitespaces:
>>> import string
>>> ws = set(string.whitespace)
The filter builtin:
>>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
'stripmyspaces'
A list comprehension (yes, use the brackets: see benchmark below):
>>> import string
>>> "".join([c for c in "strip my spaces" if c not in ws])
'stripmyspaces'
A fold:
>>> import functools
>>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
'stripmyspaces'
Benchmark:
>>> from timeit import timeit
>>> timeit('"".join("strip my spaces".split())')
0.17734256500003198
>>> timeit('"strip my spaces".translate(ws_dict)', 'import string; ws_dict = {ord(ws):None for ws in string.whitespace}')
0.457635745999994
>>> timeit('re.sub(r"\s+", "", "strip my spaces")', 'import re')
1.017787621000025
>>> SETUP = 'import string, operator, functools, itertools; ws = set(string.whitespace)'
>>> timeit('"".join([c for c in "strip my spaces" if c not in ws])', SETUP)
0.6484303600000203
>>> timeit('"".join(c for c in "strip my spaces" if c not in ws)', SETUP)
0.950212219999969
>>> timeit('"".join(filter(lambda c: c not in ws, "strip my spaces"))', SETUP)
1.3164566040000523
>>> timeit('"".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))', SETUP)
1.6947649049999995
Final line of code:
' '.join(word.strip() for word in message_text.split()
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'
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
Here's another way using plain old list comprehension:
''.join([c for c in aString if c not in [' ','\t','\n']])
Example:
>>> aStr = 'aaa\nbbb\t\t\tccc '
>>> print(aString)
aaa
bbb ccc
>>> ''.join([c for c in aString if c not in [' ','\t','\n']])
'aaabbbccc'