天天學點Python Cookbook(二)

1.過濾字符串中不屬於指定集合的字符


任務
給定一個須要保留的字符的集合,構建一個過濾函數,並可將其應用於任何字符串s,函數返回一個s的拷貝,該拷貝只包含指定字符集合中的元素。app

解決方案
能夠用string對象的translate方法。translate() 方法根據參數table給出的表(包含 256 個字符)轉換字符串的字符,要過濾掉的字符放到 deletechars 參數中。用maketrans() 方法用於建立字符映射的轉換表,具體代碼以下:函數

def make_filter(s,filter_word):
    table = str.maketrans(filter_word, ' '*len(filter_word))
    return s.translate(table).replace(' ','')

測試用例測試

if __name__ == '__main__':
    input = 'study makes me happy '
    just_vowels = make_filter(input,'aeiou')
    print(just_vowels)

測試結果spa

clipboard.png

相關文章
相關標籤/搜索