Python正则表达式将以空格分隔的单词分隔成一个列表 [英] Python regex separate space-delimited words into a list

查看:764
本文介绍了Python正则表达式将以空格分隔的单词分隔成一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串="hello world示例文本"

If I have a string = "hello world sample text"

我希望能够将其转换为列表= ["hello","world","sample","text"]

I want to be able to convert it to a list = ["hello", "world", "sample", "text"]

我该如何使用正则表达式呢? (其他不使用re的方法也是可以接受的)

How can I do that with regular expressions? (other methods not using re are acceptable)

推荐答案

"hello world sample text".split()

将在任何空格上分割.如果您只想分割空格

will split on any whitespace. If you only want to split on spaces

"hello world sample text".split(" ")

正则表达式的版本应该是这样的

regex version would be something like this

re.split(" +", "hello world sample text")

如果单词之间有多个空格,则可以使用

which works if you have multiple spaces between the words

这篇关于Python正则表达式将以空格分隔的单词分隔成一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆