在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)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值