我想知道如何追加和弹出字符串的特定元素
def letter(item):
lst = []
for i in item:
if 'a' in item:
# not sure what to put here
return lst
输出:
lst = [' a']
我只希望函数在'a'
中附加字母'apple'
,这可能吗?
有没有办法只使用list.pop()
函数从字符串中删除特定字母?
答案 0 :(得分:0)
如果您需要使用list.pop(),您可以先将字符串转换为列表:
def find_letter(item):
lst = []
item=list(item) #convert your string to list
for index,letter in enumerate(item):
if letter=='a':
lst.append(letter) # add 'a' to your empty list
item.pop(index) # remove 'a' from the original string
item="".join(item) # convert back your list to a string
return lst,item
这给出了以下输出:
>>> find_letter("apple")
>>> (['a'], 'pple')
请注意,使用列表推导可以更简单:
def find_letter(item):
word="".join([letter for letter in item if letter!='a'])
lst=[letter for letter in item if letter=='a']
return lst,word