Python2.7勉強中。
処理とか
インクリメント、デクリメント演算子はない
インクリメントは i = i+1で
forはリストの中身で繰り返し処理するもの
他言語のようなfor (i=0 ; i<10 ; i++)のようなループはない
whileを使うとか
cnt = 0
while cnt<10:
print cnt
cnt += 1
range関数で指定範囲のリストを作ってforで回す
for i in range(10):
print i
文字列関係
文字列+数値の連結はエラーになる
変数は最初に定義した型で規定される。
数値はいったん文字列に変換してから連結する
print 'abc'+str(123)
またはformatを使うとか
print 'abc{0}'.format(123)
文字列は基本的にバイト文字列。unicode文字列を扱う時は、明示的に'unicode文字列だよ'と宣言しないといけない
print len('あいうえお')
# 15
print len(u'あいうえお')
print len('あいうえお'.decode('utf-8'))
print len(unicode('あいうえお', 'utf-8'))
# 上記の結果は全部5
フォーマット出力
sprintfっぽいもの
'%s %d %f' % ('あいうえお', 10, 1.2345)
format関数
print '{0} {1} {2}'.format('あいうえお', 10, 1.2345)
%を使ったsprintfっぽいやつは、sprintfと同様のフラグが使える
print '%s %04d %.2f' % ('あいうえお', 10, 1.2345)
# あいうえお 0010 1.23
unicode文字列のフォーマット出力
以下のコードはエラーになる
print '{0} {1} {2}'.format(u'文字列', 10, 1.5)
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
正解はフォーマット文字列もunicode文字列にする
print u'{0} {1} {2}'.format(u'文字列', 10, 1.5)
# 文字列 10 1.5