# 數據類型轉換
> 原文: [https://thepythonguru.com/datatype-conversion/](https://thepythonguru.com/datatype-conversion/)
* * *
于 2020 年 1 月 7 日更新
* * *
偶爾,您會希望將一種類型的數據類型轉換為另一種類型。 數據類型轉換也稱為類型轉換。
## 將`int`轉換為`float`
* * *
要將`int`轉換為`float`,可以使用`float()`函數。
```py
>>> i = 10
>>> float(i)
10.0
```
## 將`float`轉換為`int`
* * *
要將`float`轉換為`int`,您需要使用`int()`函數。
```py
>>> f = 14.66
>>> int(f)
14
```
## 將字符串轉換為`int`
* * *
要將`string`轉換為`int`,請使用`int()`函數。
```py
>>> s = "123"
>>> int(s)
123
```
**提示**:
如果字符串包含非數字字符,則`int()`將引發`ValueError`異常。
## 將數字轉換為字符串
* * *
要將數字轉換為字符串,請使用`str()`函數。
```py
>>> i = 100
>>> str(i)
"100"
>>> f = 1.3
str(f)
'1.3'
```
## 舍入數字
* * *
四舍五入數字是通過`round()`函數完成的。
**語法**:`round(number[, ndigits])`
```py
>>> i = 23.97312
>>> round(i, 2)
23.97
```
接下來,我們將介紹[控制語句](/python-control-statements/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象