Python

モジュールをスクリプトとして実行

モジュールの最後に、 if __name__ == "__main__": # 実行させたいコード の様なifブロックを作り、スクリプトとして実行させたい内容を記述する。 ↓のコードを記述した場合、 if __name__ == "__main__": import sys fib(int(sys.argv[1])) mainファイルと…

アサーション

assert 条件式, 説明 i = 10 assert i <= 9, "i is out of range. i: " + str(i) # AssertionError: i is out of range. i: 10 ↑のコードは↓と等価 if __debug__: if not i <= 9: raise AssertionError("i is out of range. i: " + str(i)) ビルトイン変数 _…

リストのコピー

リストへの参照を渡すときは、 lst_ref = lst_org中身をコピーした新しいリストを渡すときは[:]を付ける lst_cp = lst_org[:] lst_org = ['apple', 'banana', 'orange'] lst1 = lst_org # リストオブジェクトへの参照を渡す lst2 = lst_org[:] # 中身をコピ…

python3.0のシンタックスハイライト

最新のシンタックスファイルに入れ替えた。 python.vim - Enhanced version of the python syntax highlighting script : vim online TrueとFalseがハイライトされてなかったので、python3.0.vimの中身をみたら、オプションがあった。 .vimrcに以下を記述し…

ファイル読み書き (Python v3.1.1 ドキュメントメモ)

ドキュメント覚え書きと練習したコードのメモ Open http://docs.python.org/3.1/tutorial/inputoutput.html#reading-and-writing-files # open()はファイルオブジェクトを返す f = open('/tmp/workfile', 'w') 第一引数はファイルパス 第二引数はモード(省略…

文字列のフォーマットとか (Python v3.1.1ドキュメントメモ)

ドキュメント覚え書きと練習したコードのメモ 値からStringへの変換はrepsr()またはstr()で http://docs.python.org/3.1/tutorial/inputoutput.html#fancier-output-formatting str() は人間が読めそうな表現を返す repr() はインタプリタが読める表現を返す…

Python 3.1.1 メモ

end キーワードで改行の代わりに指定した文字を行末に入れる http://docs.python.org/3.1/tutorial/controlflow.html#arbitrary-argument-lists print(b, end=' ') listをforに使うときはコピーで http://docs.python.org/3.1/tutorial/controlflow.html#for…

print を print() に置換したときのメモ

print l[1] #b → print(l[1] )#b %s/\(print\)\s\(.\+\)\(#.\+\)/\1(\2)\3print len(l) → print(len(l)) %s/\(print\)\s\(.*\)/\1(\2) その他覚え書き str("hello \"world\"") を".*"で検索したときマッチするのは、 "hello \"world\"" l = ["a","b","c","d"…