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

Python 如何在字符串之前提取单词?,python,string,Python,String,我有几个字符串如下: mylist = ['pearsapple','grapevinesapple','sinkandapple'...] 我想解析apple之前的部分,然后附加到一个新列表: new = ['pears','grapevines','sinkand'] 除了在每个字符串中找到“apple”的起始点,然后在起始点之前追加之外,还有其他方法吗?使用切片与字符串的索引方法相结合 >>> [x[:x.index('apple')] for x in mylist

我有几个字符串如下:

mylist = ['pearsapple','grapevinesapple','sinkandapple'...]
我想解析apple之前的部分,然后附加到一个新列表:

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

除了在每个字符串中找到“apple”的起始点,然后在起始点之前追加之外,还有其他方法吗?

使用切片与字符串的
索引方法相结合

>>> [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']

我不明白为什么。

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

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

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

for word in mylist:
    word = word.split("apple")[0]

我希望苹果的单词是fix(定长单词),然后我们可以使用:

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

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

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

为什么不将
str.replace“apple”替换为“”?列表中的每个元素中是否都有apple?您需要更具体地说明字符串的具体形式,想象一个列表['pearsapple','appleapple','appleapples','sinkandtoast','appleflavouredapple'],这将对许多人造成严重破坏approaches@Chris_Rands这是正确的。在我的回答中,我假设每个单词都包含子字符串“apple”(但不必以“apple”结尾),OP需要前面的所有字母。如果所有字符串都保证以“apple”结尾,并且只包含一个“apple”,这是一个很好的解决方案。是的。正当它适用于固定长度的字子字符串。:)是 啊右@drako第二个只有在每个单词中都有苹果时才有效。@timgeb:True。我们确实需要OP提供更多信息。它可以是
None
、原始字符串或空字符串。我认为原始字符串仍然比您的
AttributeError:'NoneType'
;)是一个更好的选择