Python3數據類型及轉換

  • 2020 年 1 月 17 日
  • 筆記

I. 數據類型

Python3將程式中的任何內容統稱為對象(Object),基本的數據類型有數字和字元串等,也可以使用自定義的類(Classes)創建新的類型。

Python3中有六個標準的數據類型:

  • Number(數字)
  • String(字元串)
  • List(列表)
  • Tuple(元組)
  • Set(集合)
  • Dictionary(字典)

Python3的六個標準數據類型中:

  • 不可變數據(3 個):Number(數字)、String(字元串)、Tuple(元組);
  • 可變數據(3 個):List(列表)、Dictionary(字典)、Set(集合)。

1. Number:int, float, bool, complex

a, b, c, d = 1, 2.3, True, 4+5j print(type(a), type(b), type(c), type(d), type(a+b+c+d), a+b+c+d)

<class 'int'> <class 'float'> <class 'bool'> <class 'complex'> <class 'complex'> (8.3+5j)

2. String:

Python中的字元串用單引號'或雙引號"括起來,同時使用反斜杠轉義特殊字元。r或R表示原始字元串。

s = r'this is raw string n t.' print(type(s), s)

<class 'str'> this is raw string n t.

3. List:

列表是寫在方括弧[]之間,用逗號分隔開的元素列表。列表的元素可以是數字、字元串和列表。

4. Tuple:

元組是寫在小括弧()之間,用逗號分隔開的元素列表。

t = (1, 2.3, True, 4+5j, (6, 'abc', ['d', {'id': 9, 'value': 'dict'}])) print(type(t), t)

<class 'tuple'> (1, 2.3, True, (4+5j), (6, 'abc', ['d', {'id': 9, 'value': 'dict'}]))

5. Set:

集合可以使用{}或set()函數來創建,創建空集合必須用set()。

基本功能是測試成員關係和刪除重複元素。

s1 = {1.2, 4+5j, 'abc', 'abc', 'd'} s2 = set('abcdde') print(type(s1), s1, type(s2), s2) print(s1 – s2, s1 | s2, s1 & s2, s1 ^ s2)

<class 'set'> {1.2, (4+5j), 'd', 'abc'} <class 'set'> {'c', 'a', 'd', 'e', 'b'} {1.2, (4+5j), 'abc'} {1.2, 'c', 'a', 'd', (4+5j), 'abc', 'e', 'b'} {'d'} {'c', 1.2, 'a', (4+5j), 'abc', 'e', 'b'}

6. Dictionary:

字典通過{}或dict()函數創建,是無序的key:value映射的集合。key必須為不可變類型且唯一。

d1 = {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}, (True, 4+5j): [1, 'abc']} d2 = dict([(1, 'abc'), ('name', {'cn': 'Chinese name', 'en': 'English name'})]) d3 = dict(name={'cn': 'Chinese name', 'en': 'English name'}, one='abc') print(type(d1), d1, d1[(True, 4+5j)]) print(type(d2), d2, d2[1]) print(type(d3), d3, d3['one'])

<class 'dict'> {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}, (True, (4+5j)): [1, 'abc']} [1, 'abc'] <class 'dict'> {1: 'abc', 'name': {'cn': 'Chinese name', 'en': 'English name'}} abc <class 'dict'> {'name': {'cn': 'Chinese name', 'en': 'English name'}, 'one': 'abc'} abc

II.數據類型轉換

參考:簡明Python教程(英文原版)、菜鳥教程 數據類型轉換