pythonはC言語など他の言語と比較して型に寛容で、変数に格納した文字列を読み取り自動的に設定を行ってくれます。しかし、型を知らなくても大丈夫というわけではないので、今回は公式サイトのドキュメントを参考に変数型についてまとめてみました。
数値型
int(整数)
>>> 2 + 2 4
float(浮動小数点)
小数部切り捨てなし
>>> 17 / 3 5.666666666666667
小数部切り捨てあり
>>> 17 // 3 5
剰余
>>> 17 % 3 2
文字列型
string
シングルクォーテーションで囲む
>>> 'spam eggs' 'spam eggs'
シングルクォーテーションが文字列内にある場合、\で表記可能
>>> 'doesn\'t' "doesn't"
文字列はインデックス表記可能
>>> word = 'Python' >>> word[0] # character in position 0 'P' >>> word[5] # character in position 5 'n' >>> word[-1] # last character 'n'
文字列はスライス可能
>>> word = 'Python' >>> word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py' >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho' >>> word[:2] # character from the beginning to position 2 (excluded) 'Py' >>> word[4:] # characters from position 4 (included) to the end 'on' >>> word[-2:] # characters from the second-last (included) to the end 'on'
組込み関数 len() は文字列の長さ (length) を返す
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
リスト型
list
>>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25]
リスト型でもインデックス表記可能
>>> squares[0] # indexing returns the item 1 >>> squares[-1] 25 >>> squares[-3:] # slicing returns a new list [9, 16, 25]
リスト型でも組込み関数 len() 使用可能
>>> letters = ['a', 'b', 'c', 'd'] >>> len(letters) 4
入れ子にすることも可能
>>> a = ['a', 'b', 'c'] >>> n = [1, 2, 3] >>> x = [a, n] >>> x [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b'
タプル型
tuple
>>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!')
入れ子にすることも可能
>>> u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
集合型
set
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been removed {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False
論理演算も可能
>>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'}
辞書型(連想配列)
dict
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
辞書に追加
>>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098}
keyからvalueを取得
>>> tel['jack'] 4098
辞書から削除
>>> del tel['sape']
コメント