How do i get rid of extra spaces in python?
Using regexes with "\s" and doing simple string.split()'s will also remove other whitespace - like newlines, carriage returns, tabs. Unless this is desired, to only do multiple spaces, I present these examples. Show I used 11 paragraphs, 1000 words, 6665 bytes of Lorem Ipsum to get realistic time tests and used random-length extra spaces throughout:
The one-liner will essentially do a strip of any leading/trailing spaces, and it preserves a leading/trailing space (but only ONE ;-).
NOTE: The "
For the trivial string, it would seem that a while-loop is the fastest, followed by the Pythonic string-split/join, and regex pulling up the rear. For non-trivial strings, seems there's a bit more to consider. 32-bit 2.7? It's regex to the rescue! 2.7 64-bit? A In the end, one can improve performance if/where/when needed, but it's always best to remember the mantra:
IANAL, YMMV, Caveat Emptor! How do I remove extra spaces between words in a string Python?Using re. sub() or split() + join() method to remove extra spaces between words in Python.
How do you remove extra spaces from a string?Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s .
How do you strip all spaces in Python?Let's go through each of these options and when you should use them.. str. strip()—Remove Leading and Trailing Spaces. The str. ... . str. replace()—Remove All White Spaces. ... . str. join() and str. ... . str. translate()—Remove Tabs, Newlines, and Other White Spaces. ... . re. sub()—Replace White Spaces with Empty Strings.. |