Python正则表达式将以空格分隔的单词分隔为一个列表

时间:2010-12-08 00:21:23

标签: python regex string list

如果我有一个string =“hello world sample text”

我希望能够将其转换为list = [“hello”,“world”,“sample”,“text”]

如何使用正则表达式执行此操作? (其他不使用re的方法是可以接受的)

1 个答案:

答案 0 :(得分:18)

"hello world sample text".split()

将在任何空格上分割。如果你只想分隔空格

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

正则表达式版本就是这样的

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

如果单词之间有多个空格

,则有效