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'
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Taking advantage of str.split’s behavior with no sep parameter:
If you just want to remove spaces instead of all whitespace:
Premature optimization
Even though efficiency isn’t the primary goal—writing clear code is—here are some initial timings:
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:
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.