代码之家  ›  专栏  ›  技术社区  ›  wrongusername

如何从字符串中删除所有空白

  •  150
  • wrongusername  · 技术社区  · 16 年前

    如何去除python字符串中的所有空格?例如,我想要一个像 strip my spaces 变成 stripmyspaces 但是我似乎不能用 strip() :

    >>> 'strip my spaces'.strip()
    'strip my spaces'
    
    10 回复  |  直到 7 年前
        1
  •  259
  •   Roger Pate    16 年前

    >>> s = " \t foo \n bar "
    >>> "".join(s.split())
    'foobar'
    

    >>> s.replace(" ", "")
    '\tfoo\nbar'
    

    $ 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
    

    $ 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
    

        2
  •  49
  •   Tim Yates    16 年前
    >>> import re
    >>> re.sub(r'\s+', '', 'strip my spaces')
    'stripmyspaces'
    

        3
  •  27
  •   Mirek Długosz    9 年前

    "strip my spaces".translate( None, string.whitespace )
    

    "strip my spaces".translate(str.maketrans('', '', string.whitespace))
    
        4
  •  12
  •   carl    16 年前

    "foo bar\t".replace(" ", "").replace("\t", "")
    

    import re
    re.sub(r"\s", "", "foo bar\t")
    
        5
  •  4
  •   Gabriel M RandayO    7 年前

    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(" ", "")
    
        6
  •  3
  •   Matthew Iselin    16 年前

    re.sub

    \s in the manual

        7
  •  3
  •   PrabhuPrakash    9 年前
    import re
    re.sub(' ','','strip my spaces')
    
        8
  •  2
  •   Yogesh Awdhut Gadade    7 年前

    s = " \t foo \n bar "
    "".join(s.split())
    'foobar'
    

    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
    
        9
  •  0
  •   R. Arctor    7 年前

    def remove_spaces(in_string: str):
        return in_string.translate(str.maketrans({' ': ''})
    

    import string
    def remove_whitespace(in_string: str):
        return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))
    

    str.translate Full documentation for str.translate

    str.maketrans str Full documentation for str.maketrans

    string string.whitespace Full documentation for string

    dict.fromkeys None Full documentation for dict.fromkeys

        10
  •  0
  •   jferard    7 年前

    split/join translate

    >>> import string
    >>> ws = set(string.whitespace)
    

    filter

    >>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
    'stripmyspaces'
    

    >>> import string
    >>> "".join([c for c in "strip my spaces" if c not in ws])
    'stripmyspaces'
    

    >>> import functools
    >>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
    'stripmyspaces'
    

    >>> 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