Python.use(better) #ASCII: step03 -- [chr(e) for e in ...]
‖記事一覧‖ Python.use(better)《Python3.1》
[chr(e) for e in ...]
《著》森こねこ、小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28
課題を作成する過程を通して「文字列処理」の理解を深めます。
※ Python1.5 で作成した例題を、Python3.1 で再構成しました。
事例:コードの解説
class ASCII(object): def __init__(self): self.cset = self._cset() def _cset(self): start,stop = "@Z" s = ord(start), ord(stop)+1 return [chr(e) for e in range(*s)] def __iter__(self): for e in self.cset: yield e def __repr__(self): return "".join(self)
■ #1: 内包を使って
## ---------------------------------------- before def _cset(self): s = [] ... for e in range(ord(start), ord(stop)+1): s.append(chr(e)) return s ## ---------------------------------------- after def _cset(self): ... s = ord(start), ord(stop)+1 return [chr(e) for e in range(*s)]
for 文と同等のものは「内包」を使うと、より簡潔に記述できます。
■ #2: pack/unpack
## ---------------------------------------- before start,stop = "@","Z" ## ---------------------------------------- after start,stop = "@Z"
変数 start,stop は、文字列の各要素(長さ1の文字列)を保持します。
■ #3: pack/unpack
## ---------------------------------------- before for e in range(ord(start), ord(stop)+1): s.append(chr(e)) ## ---------------------------------------- after s = ord(start), ord(stop)+1 return [chr(e) for e in range(*s)]
実引数に * を付けると、シーケンス s(タプル)の各要素を展開したものが、実引数に指定されます。
事例:モジュールを起動する
■ 全項目を確認する
全ステップの「項目」を確認するには、関数 do を利用します。
$ python -i ascii.py >>> do() 0: step00 -- class ASCII(object): 1: step01 -- def __init__(self): 2: step02 -- def _cset(self): 3: step03 -- [chr(e) for e in ...] 4: step04 -- def _body(self): 5: step05 -- c = " \n"[not (i+1)%16] 6: step06 -- [e+" \n"[not (i+1)%16] 7: step07 -- def _header(self): 8: step08 -- def _title(self): 9: step09 -- def _body(self): >>>