Python 中按空格分割字符串
我正在寻找相当于Python的
String str = "many fancy word \nhello \thi";
String whiteSpaceRegex = "\\s";
String[] words = str.split(whiteSpaceRegex);
["many", "fancy", "word", "hello", "hi"]
I'm looking for the Python equivalent of
String str = "many fancy word \nhello \thi";
String whiteSpaceRegex = "\\s";
String[] words = str.split(whiteSpaceRegex);
["many", "fancy", "word", "hello", "hi"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
str.split()
不带参数的方法在空格上分割:The
str.split()
method without an argument splits on whitespace:使用 split() 将是最 Pythonic 的字符串分割方式。
记住如果您在没有空格的字符串上使用
split()
,那么该字符串将在列表中返回给您,这一点也很有用。例子:
Using
split()
will be the most Pythonic way of splitting on a string.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.Example:
另一种方法是通过
re
模块。它执行相反的操作,匹配所有单词,而不是按空格吐出整个句子。上述正则表达式将匹配一个或多个非空格字符。
Another method through
re
module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.Above regex would match one or more non-space characters.