本文翻译自: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)