2016-01-20 76 views
0

我想知道如何追加和彈出一個字符串只有特定的元素時,彈出一個字符串列表中的特定元素追加/遍歷它

def letter(item): 

    lst = [] 
    for i in item: 
     if 'a' in item: 
      # not sure what to put here 
    return lst 

輸出:

LST = [」 a']

我只希望函數在'apple'中附加字母'a',這是可能的嗎?

有沒有辦法只使用list.pop()函數從字符串中刪除特定字母?

+0

Python code-smell#4:在迭代它時修改數組。 –

+0

你是什麼意思?當'item'爲''apple''時給'lst = ['a']'? –

+0

是的,只在第一個返回'a',所以第一個將會是lst = [a'] – Vellop

回答

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 
+0

謝謝,那正是我要找的。 – Vellop

+0

不客氣,請考慮接受答案,如果這是你需要的;) – CoMartel