50个标题在一行,有的包含空格,有的不包含空格。如何用Python对标题进行拆分
时间: 2024-03-03 17:48:13 浏览: 13
你可以使用Python中的正则表达式模块`re`来对标题进行拆分。以下是一个示例代码,可以将每个标题拆分成一个列表中的单独元素:
``` python
import re
# 假设你的标题存储在一个字符串变量中,名为titles
titles_string = "title1 title2 title3 title4 title5 title6 title7 title8 title9 title10 title11 title12 title13 title14 title15 title16 title17 title18 title19 title20 title21 title22 title23 title24 title25 title26 title27 title28 title29 title30 title31 title32 title33 title34 title35 title36 title37 title38 title39 title40 title41 title42 title43 title44 title45 title46 title47 title48 title49 title50"
# 使用正则表达式进行拆分
titles_list = re.findall(r'\S+', titles_string)
# 输出拆分后的结果
print(titles_list)
```
在上面的代码中,我们使用`\S+`正则表达式来匹配所有不包含空格的单词,然后使用`re.findall()`方法来查找所有匹配的单词并将它们存储在一个列表中。这样,你就可以轻松地对标题进行拆分。