如何在某些字符串之前提取单词?

时间:2017-05-23 13:19:12

标签: python string

我有几个这样的字符串:

mylist = ['pearsapple','grapevinesapple','sinkandapple'...]

我想在apple之前解析部分,然后附加到新列表中:

new = ['pears','grapevines','sinkand']

除了找到“苹果”的出发点之外,还有其他方法吗?在每个字符串中然后在起点之前附加?

5 个答案:

答案 0 :(得分:2)

将切片与index字符串方法结合使用。

>>> [x[:x.index('apple')] for x in mylist]
['pears', 'grapevines', 'sinkand']

您也可以使用正则表达式

>>> import re
>>> [re.match('(.*?)apple', x).group(1) for x in mylist]
['pears', 'grapevines', 'sinkand']

我不明白为什么。

答案 1 :(得分:2)

我希望apple这个词会被修复(固定长度的单词),然后我们可以使用:

second_list = [item[:-5] for item in mylist]

答案 2 :(得分:2)

如果列表中的某些元素在字符串的末尾不包含'apple',则此正则表达式保持字符串不变:

>>> import re
>>> mylist = ['pearsapple','grapevinesapple','sinkandapple', 'test', 'grappled']
>>> [re.sub('apple$', '', word) for word in mylist]
['pears', 'grapevines', 'sinkand', 'test', 'grappled']

答案 3 :(得分:1)

还使用字符串拆分和列表理解

new = [x.split('apple')[0] for x in mylist]
['pears', 'grapevines', 'sinkand']

答案 4 :(得分:0)

一种方法是迭代列表中的每个字符串,然后使用split()字符串函数。

for word in mylist:
    word = word.split("apple")[0]
相关问题