---
# System prepended metadata

title: Python常用function與method

---

# Python常用function與method


## 數字（Number）
### Function
- floor(num)
	- 無條件捨去小數點位
	```python
	>>> import math
	>>> my_num = 3.14
	>>> print(math.floor(my_num))
	3
	```

## 字串（String）
### Method
- str.split(str="", num=string.count(str))
	- 將字串以指定的字串做分隔，默認以所有空字符做分隔，參數num可以指定要分隔幾次，若沒有指定則全部做分隔
	```python
	>>> my_str = "I have a dream"
	>>> print(my_str.split(" "))
	['I', 'have', 'a', 'dream']
	```
- str.join(seq)
	- 將序列以指定的字符串起來形成一個新的字串
	```python
	>>> my_list = ['I', 'have', 'a', 'dream']
	>>> print(" ".join(my_list))
	I have a dream
	```
- str.lower()
	- 將字串大寫的字符轉成小寫
	```python
	>>> my_str = "I Have A Dream"
	>>> print(my_str.lower())
	i have a dream
    ```
- str.upper()
	- 將字串小寫的字符轉成大寫
	```python
	>>> my_str = "I Have A Dream"
	>>> print(my_str.upper())
	I HAVE A DREAM
	```
- str.strip([chars])
	- 移除在字串頭尾出現的指定字符，默認為空白
	```python
	>>> my_str = " I have a dream    "
	>>> print(my_str.strip())
	i have a dream
	```
- str.isdigit()
	- 判別字串是否為數字所有組成
	```python
	>>> my_str = "123"
	>>> print(my_str.isdigit())
	True
	```
- str.startswith(substr, beg=0,end=len(string))
	- 判斷字串是否以所指定的參數字串開頭
	```python
	>>> my_str = "I have a dream"
	>>> print(my_str.startswith("I"))
	True
	```
- str.replace(old, new [, max])
	- 將字串的某一字串換成另一個字串
	```python
	>>> my_str = "I have a dream"
	>>> print(my_str.replace("a dream", "an apple"))
	I have an apple
	```
- str.count(substr, beg= 0, end=len(string))
	- 統計某字串在此字串出現幾次
	```python
	>>> my_str = "national taiwan university"
	>>> print(my_str.count("a"))
	4
	```
- str.format()
	- 格式化字串
	```python
	>>> my_str = "Monday"
	>>> print("Today is {}.".format(my_str))
	Today is Monday.
	```
### Function
- len(str)
	- 回傳有多少個字元數
	```python
	>>> my_str = "I have a dream."
	>>> print(len(my_str))
	15
	```
- int(str)
    - 將字串轉為數字
    ```python
    >>> my_str = '123'
    >>> my_int = int(my_str)
    >>> print(my_int)
	123
    >>> print(type(my_int))
    <class 'int'>
    ```
	
## 列表（List）
### Method
- list.count(obj)
	- 統計某個元素在列表出現的次數
	```python
	>>> my_list = [1, 3, 1, 4, 5, 2, 0]
	>>> print(my_list.count(1))
	2
	```
- list.insert(index, obj)
	- 在指定index位置插入新的元素進去
	```python
	>>> my_list = [1, 3, 4, 5, 2, 0]
	>>> my_list.insert(2, 1)
	>>> print(my_list)
	[1, 3, 1, 4, 5, 2, 0]
	```
- list.sort(key=None, reverse=False)
	- 將列表排序，可以透過key指定更詳細的排序方法，reverse為顛倒排序順序
	```python
	>>> my_list = [1, 3, 1, 4, 5, 2, 0]
	>>> my_list.sort()
	>>> print(my_list)
	[0, 1, 1, 2, 3, 4, 5]
	```
### Function
- len(list)
	- 回傳列表中元素個數
	```python
	>>> my_list = [1, 3, 1, 4, 5, 2, 0]
	>>> print(len(my_list))
	7
	```
- max(list)
	- 回傳列表中最大的元素
	```python
	>>> my_list = [1, 3, 1, 4, 5, 2, 0]
	>>> print(max(my_list))
	5
	```
- sorted(list, cmp=None, key=None, reverse=False)
	- 將列表做排序
	```python
	>>> my_list = [1, 3, 1, 4, 5, 2, 0]
	>>> print(sorted(my_list))
	[0, 1, 1, 2, 3, 4, 5]
	```
- enumerate(list, [start=0])
	- 回傳列表索引序列，由元素和元素編號所組成
	```python
	>>> my_list = ["Start", "Pause", "End"]
	>>> print(list(enumerate(my_list)))
	[(0, 'Start'), (1, 'Pause'), (2, 'End')]
	```
## 集合（Set）
### Method
- set.add(obj)
	- 給集合添加元素
	```python
	>>> my_set = {"Apple", "Banana", "Coconut"}
	>>> my_set.add("Orange")
	>>> print(my_set)
	{'Banana', 'Orange', 'Coconut', 'Apple'}
	```
- set.update(set)
	- 添加新的集合至當前集合
	```python
	>>> my_set = {"Apple", "Banana", "Coconut"}
	>>> my_set_2 = {"Orange", "Watermelon"}
	>>> my_set.update(my_set_2)
	>>> print(my_set)
	{'Orange', 'Coconut', 'Apple', 'Watermelon', 'Banana'}
	```
- set.intersection(set1, set2 ... etc)
	- 回傳集合與參數中所列集合的交集
	```python
	>>> my_set = {"Apple", "Banana", "Coconut"}
	>>> my_set_2 = {"Apple", "Orange"}
	>>> print(my_set.intersection(my_set_2))
	{'Apple'}
	```
### Function

## 字典（Dict）
### Method
- dict.has_key(key)
	- 查看所指定的key是否是字典的鍵
	```python
	>>> my_dict = {"Name": "TA", "Age": 18}
	>>> print(my_dict.has_key("Apple"))
	False
	```
- dict.keys()
	- 列出字典中所有的鍵
	```python
	>>> my_dict = {"Name": "TA", "Age": 18}
	>>> print(my_dict.keys())
	dict_keys(['Name', 'Age'])
	```
- dict.values()
	- 列出字典中所有的值
	```python
	>>> my_dict = {"Name": "TA", "Age": 18}
	>>> print(my_dict.values())
	dict_values(['TA', 18])
	```
- dict.items()
	- 列出字典中所有的(鍵, 值)
	```python
	>>> my_dict = {"Name": "TA", "Age": 18}
	>>> print(my_dict.items())
	dict_items([('Name', 'TA'), ('Age', 18)])
	```
- dict1.update(dict2)
	- 把字典dict2的鍵值更新到dict裡
	```python
	>>> my_dict = {"Taiwan": "Taipei", "Japan": "Tokyo"}
	>>> my_dict_2 = {"USA": "New Work", "Canada": "Ottawa"}
	>>> my_dict.update(my_dict_2)
	>>> print(my_dict)
	{'Taiwan': 'Taipei', 'Japan': 'Tokyo', 'USA': 'New Work', 'Canada': 'Ottawa'}
	```
- dict.pop(key[,default])
	- 刪除字典裡所指定的鍵並回傳對應的值，若key不存在回傳default
	```python
	>>> my_dict = {"Taiwan": "Taipei", "Japan": "Tokyo"}
	>>> my_dict.pop("Japan")
	>>> print(my_dict)
	{'Taiwan': 'Taipei'}
	```
### Function

## 型態轉換（Type Conversion）
- int(x)
	- 將x轉換成整數
	```python
	>>> my_str = "123"
	>>> my_num = int(my_str)
	>>> print(type(my_num))
	<class 'int'>
	```
- str(x)
	- 將x轉換成字串
	```python
	>>> my_num = 123
	>>> my_str = str(my_num)
	>>> print(type(my_str))
	<class 'str'>
	```
- list(x)
	- 將x轉換成列表
	```python
	>>> my_str = "abcde"
	>>> print(list(my_str))
	['a', 'b', 'c', 'd', 'e']
	```
- dict(x)
	- 將x轉換成字典
	```python
	>>> my_list = [(1, "A"), (2, "B")]
	>>> print(dict(my_list))
	{1: 'A', 2: 'B'}
	```

## 輸入與輸出（Input and Output）
### 鍵盤輸入
#### Function
- input()
	- 從鍵盤讀入輸入，返回字串
	```python
	>>> ans = input("Are you over 18? ")
	Are you over 18? Y
	>>> print(ans)
	Y
	```
### 檔案（File）
#### Function
- open(filename, mode="r")
	- 開啟檔案，可以指定用什麼模式，e.g. 讀、寫、續寫...
	```python
	>>> file = open("test.txt", "r")
	```
#### Method
- file.close()
	- 把file關掉，之後無法讀寫
	```python
	>>> file = open("test.txt", "r")
	>>> file.close()
	```
- file.write(str)
	- 將字串寫入檔案
	```python
	>>> file = open("test.txt", "r")
	>>> file.write("I am a coder")
	>>> file.close()
	```
- file.read([size])
	- 讀取檔案，若沒有指定大小，則全部內容全會被讀取
	```python
	>>> file = open("test.txt", "r")
	>>> content = file.read()
	>>> print(content)
	<line 1 content ...>
	<line 2 content ...>
	```
- file.readline([size])
	- 讀取檔案一行
	```python
	>>> file = open("test.txt", "r")
	>>> line_1 = file.readline()
	>>> print(line_1)
	<line 1 content ...>
	```

## OS
- os.listdir(path)
	- 列出該路徑下有的資料夾或檔案名稱
	```python
	>>> import os
	>>> print(os.listdir("./")) # ./ 指的是當前目錄
	['Music', 'Videos']
	```
## 其他內建函數
- range(start, stop[, step])
	- 回傳一個整數列表，可以依照指定從哪個數字開始，哪個數字結束，並以多少作為等差
	```python
	>>> range(0, 10, 3)
	[0, 3, 6, 9]
	```