組み込みツール

ツール(モジュール)の使い方は「ライブラリレファレンス」を参照する。 ライブラリレファレンスは、Windows 用にはスタートメニューから開くことができるが、 ネット上でも、Python Documentation Site から、Library Reference ( 日本語訳プロジェクト) をたどると見ることができる。

また、dir() を使うとオブジェクトが持っている属性(内部データ、メソッド関数)を 調べることができ、type() を使うと「型」を調べることができる。

sys モジュール

組み込み関数

型変換、属性の操作、プログラムの実行など

プログラムの実行

>>> code = "x = 'Something'"
>>> x = "Nothing"
>>> exec code
>>> x
'Something'
>>> dict = {'x': 'Anything'}
>>> code = "print x"
>>> exec code in dict
Anything
>>> z = eval("'xo'*10")
>>> z
'xoxoxoxoxoxoxoxoxoxo'

文字列の操作

新しいバージョンの Python では、string モジュールのほとんどの機能は、 文字列型オブジェクトのメソッドになっている。
>>> a = 'tomato'
>>> a.capitalize()
'Tomato'
>>> a = 'tomato\tpotato'
>>> a
'tomato\tpotato'
>>> print a
tomato	potato
>>> a.expandtabs()
'tomato  potato'
>>> a = 'now is the time'
>>> a.find('is')
4
>>> a.count('i')
2
>>> a.replace(' ', '_')
'now_is_the_time'
>>> a.split(' ')
['now', 'is', 'the', 'time']
>>> x = '*'
>>> x.join(a.split(' '))
'now*is*the*time'
>>> "   before and after   ".strip()
'before and after'

高度な文字操作: re モジュール

正規表現

基本的な使い方の例
>>> import re
>>> s = 'abc def 012 xyz'
>>> re.match('a.*z',s)
<_sre.SRE_Match object at 0x00A98020>
>>> re.match('abc',s)
<_sre.SRE_Match object at 0x00AA0020>
>>> re.match('def',s)
>>> re.search('def',s)
<_sre.SRE_Match object at 0x00AA6140>
>>> x = re.search('def',s)
>>> x.start(), x.end()
(4, 7)
>>> s[x.start():x.end()]
'def'
>>> re.sub('def','rst',s)
'abc rst 012 xyz'
>>> re.sub('\d+','',s)
'abc def  xyz'
>>> y = re.match('.* (\d+) xyz',s)
>>> y.group(1)
'012'
>>> re.sub('^.* (\d+) xyz','\g<1> yen',s)
'012 yen'
>>> import string
>>> string.atoi(y.group(1))
12
主な Special Characters (特殊文字)
"."
(Dot) 全ての文字
"^"
(Caret) 文字列の最初
"$"
文字列の最後
"*"
直前の正規表現の0回以上の繰り返し
"+"
直前の正規表現の1回以上の繰り返し
"\"
(Backslash) 次の文字と組み合わせて特別の意味のあるシーケンスを表すか、次の文字の特殊な意味を打ち消す
[]
括弧の中の文字のどれか (例 [ab] [a-zA-Z])
()
括弧の中の正規表現または適合をグループ化する
\d
数字 ([0-9])
\s
空白文字 ([ \t\n\r\f\v])
\w
英数字 ([a-zA-Z0-9_])
正規表現をコンパイルして利用する。
>>> s
'abc def 012 xyz'
>>> r = re.compile('^.* (\d+) xyz$')
>>> r.sub('\g<1> yen',s)
'012 yen'
>>> t = 'qwe asd ert 345 xyz'
>>> r.sub('\g<1> yen', t)
'345 yen'

時刻モジュール

>>> import time
>>> time.asctime(time.localtime())
'Sun Jan 13 15:42:26 2002'
>>> time.time()
1010904182.54
>>> t = time.time()
>>> u = time.localtime(t)
>>> u
(2002, 1, 13, 15, 43, 40, 6, 13, 0)
>>> g = time.gmtime(t)
>>> g
(2002, 1, 13, 6, 43, 40, 6, 13, 0)
>>> time.asctime(g)
'Sun Jan 13 06:43:40 2002'
>>> time.strftime('%Y/%m/%d %H:%M:%S',u)
'2002/01/13 15:43:40'
>>> def test():
	a = time.time()
	time.sleep(20)
	b = time.time()
	print b - a
	
>>> test()
19.9900000095

HTTP サーバ

httptest.py をスクリプトとして実行. 実行ディレクトリをルートディレクトリとして公開する HTTP サーバが できる. (実際には Apache HTTPd のような, 最初からサーバとして作られた ものを利用するほうがよい.)