Python一行勉強リスト
検索処理
result = re.match(pat, str)
パース
re.split(",", "a,b,c,d,r,e,d")
置換
re.sub(",", " ", "a,b,c,d,e")
型変換
int("123") + 1
str(1234)
大文字小文字
"hello world".upper()
先頭と末尾の文字を取り除く
", 123 ".strip(", ")
For文
for i in range(4, 10):
print i
配列宣言
a = ['spam', 'eggs', 100, 1234]
追加
a.append(4)
ソート
a.sort()
辞書
tel = {'jack': 4098, 'sape': 4139}
ファイル読み込み
>>> f=open('d:/sandbox/test.txt', 'r')
>>> f
>>> f.readline()
'このデータは\n'
>>> f.readlines()
['ぱいそんとか\n', 'るびーとかで\n', 'よみこむための\n', 'テストデータ']
>>> f.close()
ファイル書き込み
outfile = open('out.html', 'w')
outfile.write(str)
Pathの分割
>>> os.path.split("d:/test/test")
('d:/test', 'test')
文字列配列操作
>>> "test"[0:2]
'te'
後ろから切り出す
>>> "test"[-2:]
'st'
文字長
>>> len("test")
4
外部プログラムの実行(標準出力の取得付き)
import popen2
cmd = "grep -r task_t /usr/src/linux/*"
(stdout, stdin, stderr) = popen2.popen3( cmd )
for line in stdout:
print line,
ディレクトリ一覧の取得
os.listdir("./")
glob.glob("*.txt")
BeautifulSoupで整形
from BeautifulSoup import BeautifulSoup
s = BeautifulSoup("").prettify()