16.md 1.5 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# 数据类型转换

> 原文: [https://pythonspot.com/datatype-casting/](https://pythonspot.com/datatype-casting/)

Python 自动确定数据类型,以说明:

```py

x = 3
y = "text"

```

W
wizardforcel 已提交
14
它发现`x`是整数类型,`y`是字符串类型。
W
init  
wizardforcel 已提交
15

W
wizardforcel 已提交
16
函数接受某种数据类型。 例如,`print`仅接受字符串数据类型。
W
init  
wizardforcel 已提交
17 18 19

## 数据类型转换

W
wizardforcel 已提交
20
如果要打印数字,则经常需要强制转换。
W
init  
wizardforcel 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33

在下面的示例中,我们要打印两个数字,一个整数(整数)和一个浮点数。

```py
x = 3
y = 2.15315315313532

print("We have defined two numbers,")
print("x = " + str(x))
print("y = " + str(y))

```

W
wizardforcel 已提交
34
我们使用`str()`函数将变量`x`(整数)和变量`y`(浮点数)转换为字符串。
W
init  
wizardforcel 已提交
35

W
wizardforcel 已提交
36
如果我们有要存储为数字的文本怎么办? 我们将不得不再次转型。
W
init  
wizardforcel 已提交
37 38 39 40 41 42 43 44 45 46

```py
a = "135.31421"
b = "133.1112223"

c = float(a) + float(b)
print(c)

```

W
wizardforcel 已提交
47
在上面的示例中,我们将两个具有数据类型字符串的变量强制转换为数据类型`float`
W
init  
wizardforcel 已提交
48

W
wizardforcel 已提交
49
## 转换函数
W
init  
wizardforcel 已提交
50

W
wizardforcel 已提交
51
要在数据类型之间转换,可以使用:
W
init  
wizardforcel 已提交
52 53 54 55 56 57 58 59 60 61 62 63

[下载 Python 练习](https://pythonspot.com/download-python-exercises/)

| 功能 | 描述 |
| --- | --- |
| 整数(x) | 将 x 转换为整数 |
| 长(x) | 将 x 转换为长整数 |
| 浮点数(x) | 将 x 转换为浮点数 |
| str(x) | 将 x 转换为字符串。 x 可以是 float 类型。 整数或长整数。 |
| 十六进制(x) | 将 x 整数转换为十六进制字符串 |
| hr(x) | 将 x 整数转换为字符 |
| ord(x) | 将字符 x 转换为整数 |