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

使用python仅在多个空格上拆分字符串

  •  0
  • Tiger1  · 技术社区  · 12 年前

    我的目标是只在双空格上拆分下面的字符串。请参阅下面的示例字符串和使用常规拆分函数的尝试。

    我的尝试

    >>> _str='The lorry ran  into the mad man  before turning over'
    >>> _str.split()
    ['The', 'lorry', 'ran', 'into', 'the', 'mad', 'man', 'before', 'turning', 'over']
    

    理想结果:

    ['the lorry ran', 'into the mad man', 'before turning over']
    

    对于如何达到理想结果有什么建议吗?谢谢

    5 回复  |  直到 12 年前
        1
  •  2
  •   fredtantini    12 年前

    split 可以使用用于拆分的参数:

    >>> _str='The lorry ran  into the mad man  before turning over'
    >>> _str.split('  ')
    ['The lorry ran', 'into the mad man', 'before turning over']
    

    doc

    字符串拆分([sep[,最大拆分]])

    Return a list of the words in the string, using sep as the delimiter string.
    If maxsplit is given, at most maxsplit splits are
    done (thus, the list will have at most maxsplit+1 elements). 
    
    If sep is given, consecutive delimiters are not grouped together and are deemed
    to delimit empty strings (for example,
    '1,,2'.split(',') returns ['1', '', '2']). The sep argument may
    consist of multiple characters (for example, '1<>2<>3'.split('<>')
    returns ['1', '2', '3']).
    
        2
  •  2
  •   sloth    12 年前

    split 采用分隔符参数。只要过去 ' ' 到它:

    >>> _str='The lorry ran  into the mad man  before turning over'
    >>> _str.split('  ')
    ['The lorry ran', 'into the mad man', 'before turning over']
    >>>
    
        3
  •  2
  •   msvalkon    12 年前

    给你的 split() 双空格作为自变量。

    >>> _str='The lorry ran  into the mad man  before turning over'
    >>> _str.split("  ")
    ['The lorry ran', 'into the mad man', 'before turning over']
    >>> 
    
        4
  •  1
  •   logc    12 年前

    使用 re 模块:

    >>> import re
    >>> example = 'The lorry ran  into the mad man  before turning over'
    >>> re.split(r'\s{2}', example)
    ['The lorry ran', 'into the mad man', 'before turning over']
    
        5
  •  1
  •   Sukrit Kalra    12 年前

    因为,您需要在两个或多个空间上拆分,所以可以这样做。

    >>> import re
    >>> _str = 'The lorry ran    into the mad man    before turning over'
    >>> re.split("\s{2,}", _str)
    ['The lorry ran', 'into the mad man', 'before turning over']
    >>> _str = 'The lorry ran       into the mad man       before turning over'
    >>> re.split("\s{2,}", _str)
    ['The lorry ran', 'into the mad man', 'before turning over']