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

本文翻譯自:Split string on whitespace in Python [duplicate]

This question already has an answer here: 這個問題在這裏已有答案:

I'm looking for the Python equivalent of 我正在尋找Python的等價物

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

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

#1樓

參考:https://stackoom.com/question/Y2lS/在Python中的空格上拆分字符串-重複


#2樓

Another method through re module. 通過re模塊的另一種方法。 It does the reverse operation of matching all the words instead of spitting the whole sentence by space. 它執行匹配所有單詞的反向操作,而不是按空格吐出整個句子。

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

Above regex would match one or more non-space characters. 上面的正則表達式將匹配一個或多個非空格字符。


#3樓

Using split() will be the most Pythonic way of splitting on a string. 使用split()將是分裂字符串的最Pythonic方式。

It's also useful to remember that if you use split() on a string that does not have a whitespace then that string will be returned to you in a list. 記住如果在沒有空格的字符串上使用split() ,那麼該字符串將在列表中返回給您,這也很有用。

Example: 例:

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

#4樓

The str.split() method without an argument splits on whitespace: 沒有參數的str.split()方法在空格上拆分:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']

#5樓

import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章