owned this note
owned this note
Published
Linked with GitHub
---
title: Python 入門教學-資料型態
tags: python_beginner
---
# 資料型態
## 基本概念
* 物件: 在python當中,所有東西都是物件,物件的屬性如下
* identity: 物件的記憶體位置,可用`id()`查看
* type: 物件的類型,可用`type()`查看
* value: 物件的值,分為可變/不可變(mutable/immutable)
* immutable:
* Numeric types: int, float, complex
* string
* tuple
* frozen set
* mutable:
* list
* dict
* set
* bytearray
> 參考: [理解 Python object 的 mutable 和 immutable](http://wsfdl.com/python/2013/08/14/%E7%90%86%E8%A7%A3Python%E7%9A%84mutable%E5%92%8Cimmutable.html)
* 指派變數
在python當中,指派變數可以想像成把一張姓名標籤貼到物件上面。如下例,使用id()印出變數的記憶體位置,觀察兩個變數是否為同一物件:
```python=
>>> a = 7
>>> b = a
>>> id(a)
>>> id(b)
```
這個例子可以看到,a、b其實是同一個物件"7"。
:::warning
然而看到以下例子:
```python=
>>> a = "helloworld"
>>> b = "helloworld"
>>> id(a)
2917193150576
>>> id(b)
2917193150576
>>> a = "hello world"
>>> b = "hello world"
>>> id(a)
2917193150576
>>> id(b)
2917193150640
```
第一個例子,兩個變數指向同一個字串,然後記憶體位置一樣,這沒問題,跟剛剛看的例子結果一樣。
但是,當我們加入了空格,兩個變數都指向"hello world"時,記憶體位置卻不一樣了。
這是因為python的string interning(字串駐留)機制運作方式的關係。所謂的string interning就是當一個string被命名為某個變數時,python會決定要不要使用之前用過的string,以節省記憶體空間。詳細請看另一篇筆記[Python String Interning機制](https://hackmd.io/lrIcW9cOTj-88G7pSvTyow)。
:::
* 變數命名
* a~z
* A~Z
* 0~9
* _
注意: 開頭不可為數字、不可用保留字
查看保留字:
```python=
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
```
### 布林
`True`, `False`
### 數字
* 整數: `2`, `-23`, `1.23e4`
沒有整數溢位問題,可比64bits大
```python=
>>> googol = 10**100
>>> googol
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> googol * googol
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
* 浮點數
* 運算子
* `+` `-` `*` `/`
* `+=` `-=` `*=` `/=`
* //: 無條件捨去小數點
* %: 取餘數
* divmod()
```python=
>>> divmod(9, 5)
(1, 4)
```
* \*\*: 次方
* 基數
* 二進位: 0b
* 八進位: 0o
* 十六進位: 0x
### 字串
* 使用單引號或雙引號: 可在字串內用單or雙引號,跟最外面的不一樣就好
```python=
>>> "'Hi', said the Tom."
'Hi', said the Tom.
>>> '"Hi", said the Jerry.'
"Hi", said the Jerry.
```
* 多行字串: `''' '''` 或 `""" """`,會換行
```python=
>>> poem = '''我衰君少年
... 肚樓夕照前
... 子爲佛稱名
... 餓河海暗連'''
>>> print(poem)
我衰君少年
肚樓夕照前
子爲佛稱名
餓河海暗連
```
* \
* \n: 換行
* \t: tab
* \\"
```python=
>>> "\"I don't understand\""
"I don't understand"
```
* \\\: 如果要用反斜線就在他前面加上反斜線
* +: 連接字串
* \*: 複製字串
```python=
>>> "hi" * 4
'hihihihi'
```
* []: 擷取字串
```python=
>>> letters = "abcdef"
>>> letters[0]
'a'
>>> letters[-1]
'f'
```
* \[start : end : step\]: Slice
* [:]
* [start:]
* [:end]
* [start : end]
* [start : end : step]
* len()
* split()
* 更多的東西: help(str())
## 字串、Ascii轉換
* ord(): 字串轉Ascii
```python=
print(ord('a'))
```
* chr(): Ascii轉字串
```python=
print(chr(97))
```
## 型別轉換
* int(): 保留整數,捨棄小數
```python=
>>> int(True)
1
>>> int(False)
0
>>> int(87.8)
87
>>> int(1.23e4)
12300
>>> int('99')
99
>>> int('-23')
-23
```
* float()
* str()