首页 文章

在Python中的空格上拆分字符串[重复]

提问于
浏览
362

这个问题在这里已有答案:

我正在寻找Python的等价物

String str = "many   fancy word \nhello    \thi";
String whiteSpaceRegex = "\\s";
String[] words = str.split(whiteSpaceRegex);

["many", "fancy", "word", "hello", "hi"]

4 回答

  • 58

    没有参数的 str.split() 方法在空格上拆分:

    >>> "many   fancy word \nhello    \thi".split()
    ['many', 'fancy', 'word', 'hello', 'hi']
    
  • 668
    import re
    s = "many   fancy word \nhello    \thi"
    re.split('\s+', s)
    
  • 14

    另一种方法是通过 re 模块 . 它执行匹配所有单词的反向操作,而不是按空格吐出整个句子 .

    >>> import re
    >>> s = "many   fancy word \nhello    \thi"
    >>> re.findall(r'\S+', s)
    ['many', 'fancy', 'word', 'hello', 'hi']
    

    上面的正则表达式将匹配一个或多个非空格字符 .

  • 9

    使用 split() 将是分裂字符串的最Pythonic方式 .

    记住如果在没有空格的字符串上使用 split() ,那么该字符串将在列表中返回给您,这也很有用 .

    例:

    >>> "ark".split()
    ['ark']
    

相关问题