題目: 給定一個英文的字符串, 要求你將其中的元音刪除掉, 返回新的字符串.python
例如:
"This website is for losers LOL!" --> "Ths wbst s fr lsrs LL!"web
當看到這個題目的時候, 第一個想起的就是re模塊的正則表達式. 不過因爲最近使用過字符串的replace方法, 因此我給出的解決方法是:正則表達式
def disemvowel(string): remove_list = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"] # 先列出元音列表 for s in remove_list: while s in string: string = string.replace(s, "") # 將元音字符替換爲空再從新賦值回去 return string
這樣就能夠不用使用re模塊就完成了要求. 可是, 還有人給出了更精妙的解決方案:app
def disemvowel(s): return s.translate(None, "aeiouAEIOU")
還有許多其餘的解決方案, 有興趣的能夠訪問:spa
https://www.codewars.com/kata/disemvowel-trolls/solutions/python/all/best_practice日誌
這裏使用了一個字符串特別的方法, translate. 而這個方法平時我都沒怎麼注意過, 下面是官方文檔的說明:code
S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars.
返回一個字符串的副本, 因此出如今可選參數deletechars中的字符將會被移除, 而剩餘的的字符將會經過給定的轉化表進行映射替換, 這個表必須是長度256的字符串或者是None. 當爲None時就不進行映射替換.blog
因此 s.translate(None, "aeiouAEIOU") 的意思就是刪除掉特定的字符了. utf-8
而關於映射表的使用, 通常要借用string模塊, 下面是一個示例:rem
from string import maketrans in_str = "abc" out_str = "123" table = maketrans(in_str, out_str) raw_str = "abc def ghi" result = raw_str.translate(table, "ag") print result
結果:
按照方法的定義, 首先去除對應的字符, a和g在映射替換前其實已經被去掉了, 因此在進行映射替換的時候, a是不存在的, 因此並無映射替換成1, 結果也就如上所示了.
中文意義如何?
#!/usr/bin/env python # coding: utf-8 from string import maketrans in_str = "好" out_str = "壞" table = maketrans(in_str, out_str) raw_str = "你好" result = raw_str.translate(table) print result
結果:
結論: 中文無心義, 不過通常來講, 作日誌分析之類的工做時, 面對的多數是英文, 此時做用仍是很大的.