0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python初心者が引っかかったところのメモ

Posted at

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
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?