Python 中按空格分割字符串

发布于 2024-12-15 00:22:28 字数 217 浏览 3 评论 0原文

我正在寻找相当于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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

银河中√捞星星 2024-12-22 00:22:28

str.split()不带参数的方法在空格上分割:

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

The str.split() method without an argument splits on whitespace:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']
屌丝范 2024-12-22 00:22:28
import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)
import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)
太阳男子 2024-12-22 00:22:28

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

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

例子:

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

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:

>>> "ark".split()
['ark']
滥情空心 2024-12-22 00:22:28

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

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

上述正则表达式将匹配一个或多个非空格字符。

Another method through re module. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文