2013-08-27 28 views
1

新的python所以希望得到一些幫助。 試圖建立一個函數(目前爲止可悲的失敗),它的目的是從單詞中刪除指定的字母,然後返回結果。刪除已知的字符

例子:

word_func( '鳥', 'B')

返回的結果將隨後給 '稅務局' 用B下降。

我和重新啓動的功能是:

高清word_func( '字', '信'):

任何幫助,將不勝感激。我想我在我腦海中過分複雜。

+0

即使你不知道python內建的方法可以用'for'循環來嘗試。 – badc0re

回答

3

怎麼樣使用replace()

>>> def word_func(word, letter): 
...  return word.replace(letter, '') 
... 
>>> word_func('bird', 'b') 
'ird' 
+0

菜鳥錯誤清楚。我正在使用引號,我不應該和python沒有指出錯誤。這工作。 – Vox

1

Python中的所有字符串有replace功能。

>>> 'bird'.replace('b', '') 
'ird' 

哪些功能,你可以看到,很像除去字母(或字母系列)

>>> 'bird'.replace('bi', '') 
'rd' 

但是如果你想,只除去字母的第一個實例,或第一n信的情況下,你可以使用第三個參數,

>>> 'this is a phrase'.replace('s','') # remove all 
'thi i a phrae' 
>>> 'this is a phrase'.replace('s','',1) # remove first 
'thi is a phrase' 
>>> 'this is a phrase'.replace('s','',2) # remove first 2 
'thi i a phrase' 

而且你可以從最終使用一些詭計,並扭轉字符串甚至刪除。

>>> 'this is a phrase'[::-1].replace('s','',2)[::-1] # remove last 2 
'this i a phrae' 
+1

你知道'str.replace'有第三個參數;)。 – TerryA

+0

@Haidro我其實沒有..我現在感到很傻,我會更新我的答案。 –

0

你可以使用mapjoinlambda

def word_func(word, letter): 
    return "".join(map(lambda x: x if x !=letter else "",word)) 


if __name__ =="__main__": 
    word = "bird" 
    letter = "r" 
    print word_func(word, letter) 

打印:

投標

或者你可以使用filter並用拉姆達加入:

def word_func(word, letter): 
    return filter(lambda x: x !=letter, word) 

也沒必要加入輸出,因爲:

如果迭代是一個字符串或一個元組,結果也有這種類型的

+0

'「bird」.strip(「i」)'''bird''' - 這不是OP想要的。 – alecxe

+0

很棒的alecxe – Noelkd

+0

如果下來的選民可以留下評論,這將有助於改善帖子。 – Noelkd