任務:用每次處理一個字符的方式處理字符串
解決方案:
1, 可創建一個列表,其子項是字符串的字符(意思是每個子項是一個字符串,長度爲一),可以調用內建list,用字符串作爲參數:
thelist = list(thestring)
2, 也可以不創建,直接用for語句對該字符串循環遍歷:
for c in thestring:
do_something_with(c)
3, 或者使用列表推導中的for來遍歷:
results = [ do_something_with(c) for c in thestring ]
4, 再或者,和列表推導效果完全一樣,可以用內建的map函數,每次取得一個字符就調用一次函數:
results = map(do_something, thestring)
5, 如果想獲得的是該字符串的所有字符集合,還可以調用sets.Set,並將字符串作爲參數(可以用同樣方法直接調用內建的set):
import sets
magic_chars = sets.Set('abracadabra')
poppins_chars = sets.Set('supercalifragilisticexpialidocious')
print ''.join(magic_chars & poppins_chars) # 集合的交集
結果:
arcd