How to strip all whitespace from string

前端 未结 11 1889
暖寄归人
暖寄归人 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 18:57

    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
    

提交回复
热议问题