Python3 数据类型转换学习笔记

在 Python 中,数据类型转换是将一个数据类型的值转换为另一个数据类型的过程。数据类型转换在编程中经常用到,尤其是在不同数据类型间进行操作时。

类型转换函数

Python 中的数据类型转换函数包括以下几个:

  • int(x):将 x 转换为一个整数。
  • float(x):将 x 转换为一个浮点数。
  • str(x):将 x 转换为一个字符串。
  • list(x):将 x 转换为一个列表。
  • tuple(x):将 x 转换为一个元组。
  • set(x):将 x 转换为一个集合。
  • dict(x):将 x 转换为一个字典。

实例

下面我们来看几个具体的实例:

1. 将字符串转换为整数或浮点数

pythonCopy Code
# 将字符串转换为整数 num_str = '123' num_int = int(num_str) print(num_int, type(num_int)) # 将字符串转换为浮点数 num_float_str = '3.1415' num_float = float(num_float_str) print(num_float, type(num_float))

输出结果为:

Copy Code
123 <class 'int'> 3.1415 <class 'float'>

2. 将整数或浮点数转换为字符串

pythonCopy Code
# 将整数转换为字符串 num_int = 123 num_str = str(num_int) print(num_str, type(num_str)) # 将浮点数转换为字符串 num_float = 3.1415 num_float_str = str(num_float) print(num_float_str, type(num_float_str))

输出结果为:

Copy Code
123 <class 'str'> 3.1415 <class 'str'>

3. 将列表、元组或集合转换为字典

pythonCopy Code
# 将列表转换为字典 list1 = [('a', 1), ('b', 2), ('c', 3)] dict1 = dict(list1) print(dict1, type(dict1)) # 将元组转换为字典 tuple1 = (('a', 1), ('b', 2), ('c', 3)) dict2 = dict(tuple1) print(dict2, type(dict2)) # 将集合转换为字典 set1 = {('a', 1), ('b', 2), ('c', 3)} dict3 = dict(set1) print(dict3, type(dict3))

输出结果为:

Copy Code
{'a': 1, 'b': 2, 'c': 3} <class 'dict'> {'a': 1, 'b': 2, 'c': 3} <class 'dict'> {'a': 1, 'b': 2, 'c': 3} <class 'dict'>

以上就是 Python3 中数据类型转换的相关知识和几个具体的实例。