文字列のフォーマットとか (Python v3.1.1ドキュメントメモ)
ドキュメント覚え書きと練習したコードのメモ
値からStringへの変換はrepsr()またはstr()で
http://docs.python.org/3.1/tutorial/inputoutput.html#fancier-output-formatting
h = 'hello world\n' print(h) # hello world print(len(h)) # 12 print(str(h)) # hello world print(len(str(h))) # 12 print(repr(h)) # 'hello world\n' print(len(repr(h))) # 15 str(1.0/7.0) # '0.142857142857' repr(1.0/7.0) # '0.14285714285714285'
数値の表示
http://docs.python.org/3.1/tutorial/inputoutput.html#fancier-output-formatting
# 4文字分場所を取ってスペースで右に詰める x = 23 print(repr(x).rjust(4)) # 23 print('{0:4d}'.format(x)) #上と同じ出力 # ljust() や center() もある。 # 文字数がオーバーした場合は、元の文字列が返される x = 9999 print(repr(x).rjust(2)) #9999 # オーバー分がいらないときはスライスする print(repr(x).rjust(2)[:2]) #99 # ゼロ詰め print('12'.zfill(5)) # '00012'
文字列のフォーマット
http://docs.python.org/3.1/tutorial/inputoutput.html#fancier-output-formatting
http://docs.python.org/3.1/tutorial/inputoutput.html#old-string-formatting
- %演算子での指定スタイルはそのうち削除されるので、str.format()を使用するべき
# 順番で指定 print('{0} and {1}'.format('spam', 'eggs')) # spam and eggs # 名前で指定 print('This {food} is {adj}.'.format(food='banana', adj='green')) # This banana is green. # 文字列の幅も指定 t = {'Jack': 321} for name, phone in t.items(): print('{0:10} ==> {1:10d}'.format(name, phone)) #Jack ==> 321