How to strip all whitespace from string

前端 未结 11 1912
暖寄归人
暖寄归人 2020-11-28 18:25

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

11条回答
  •  臣服心动
    2020-11-28 19:13

    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'
    

    Premature optimization

    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.

提交回复
热议问题