03. 円周率
"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
>>> s = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.' >>> countList = [] >>> for item in s.split(): ... countList.append(len(item.strip(',.'))) ... >>> countList [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]
文字列の分割にはstrのsplit()
メソッドを使う。split()についてはここに書いてある。
splitするだけでは英単語のみにならない。そのため、,
と.
を文字列の末尾から取り除く処理をする。そのときに使用するのがstrのstrip()
メソッド。説明はここ
len()関数で長さを取得し、リストに格納する。