Pythonのデータ型
Pythonのデータ型
久しぶりにPython触ったけどやっぱりシンプル!
データ型
型 | 意味 |
---|---|
ブール値 | True またはFalse |
整数 | 42 , 100 などの小数点以下がない数値 |
浮動小数点数 | 3.14 のように小数点以下の部分がある数値、または10e8 |
文字列 | 文字の並び |
1. 変数、名前、オブジェクト
- Pythonでは全てがオブジェクトとして実装されている
- オブジェクトはプラスチックボックスのようなもので、オブジェクトには、ブール値、整数などのデータ型がある
- そのデータ型で何ができるかは型によって決まる
- 変数とはコンピュータのメモリの中にある値を指す名前のことで、プログラムの中で定義できる
変数名として使える文字は次
- 小文字の英字(
a
からz
まで) - 大文字の英字(
A
からZ
まで) - 数字(
0
から9
)アンダースコア
例
a
a1
a_1
しかし、数字で始まる名前は付けられない。
2. 数値
# 算術演算子 # 加算 >>> 5 + 8 13 # 減算 >>> 90 - 10 80 # 乗算 >>> 4 * 7 28 # 浮動小数点数の除算 >>> 7 / 2 3.5 # 整数の除算(切り捨て) >>> 7 // 2 3 # 剰余 >>> 7 % 3 1 # 指数 >>> 2 ** 2 4
除算をゼロで割ろうとすると、例外が起きる。
>>> 10 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero >>> 10 // 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
次のコードは同義
>>> i = 5 >>> i = i + 1 >>> i 6 >>> i = 5 >>> i += 1 >>> i 6
他のデータ型の値をfloat
に変換するには、float()
関数を使用する。
>>> float(True) 1.0 >>> float(False) 0.0
3. 文字列
- 文字列はシーケンスでイミュータブルである
# # 文字列のクォートはどちらでも良い # >>> 'hoge' 'hoge' >>> "hoge" 'hoge' >>> "I've a pen" "I've a pen" >>> 'I\'ve a pen' "I've a pen" # # 文字列の繰り返し # >>> 'hoge' * 3 'hogehogehoge' # # オフセット # >>> word = 'Python3' >>> word[0] # 最初の文字 'P' >>> word[-1] # 最後の文字 '3' >>> word[10] # 範囲外 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range_ # イミュータブルなので書き換えられない >>> word[0] = 'p' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment # 代わりにreplace()などを使用する >>> word.replace('P', 'p') 'python3' >>> word 'Python3' # # スライス # >>> word[:] # 全体 'Python3' >>> word[3:] # インデックスから最後まで 'hon3' >>> word[:2] # 最初からインデックスまで 'Py' >>> word[1:5] # 1~5まで 'ytho' >>> word[::2] # 最初から最後を2文字ごと 'Pto3' >>> word[-1::-1] # 逆 '3nohtyP' >>> word[::-1] # こちらでも可 '3nohtyP' # # 長さ # >>> len("we are") 6 >>> len(word) 7 # # 分割 # >>> string = 'hoge.foo.bar' >>> string.split('.') ['hoge', 'foo', 'bar'] >>> 'hoge foo bar'.split() # 空白の場合 ['hoge', 'foo', 'bar'] # # 結合 # >>> ' --> '.join(string.split('.')) 'hoge --> foo --> bar' # # 多彩な文字列操作 # >>> words = 'python ruby python scala' >>> words.startswith('python') # pythonで始まる文字列か True >>> words.endswith('python') # pythonで終わる文字列か False >>> words.find('python') # 左から見つけたインデックス 0 >>> words.rfind('python') # 右から見つけたインデックス 12 >>> words.capitalize() # 先頭文字を大文字に 'Python ruby python scala' >>> words.title() # 単語ごとの先頭文字を大文字に 'Python Ruby Python Scala' >>> words.ljust(40) # 左端に配置 'python ruby python scala ' >>> words.center(40) # 中央に配置 ' python ruby python scala ' >>> words.rjust(40) # 右端に配置 ' python ruby python scala' >>> words.replace('python', 'Python3') # 置換 'Python3 ruby Python3 scala'