常见的Python数据类型转换函数及其用法
发布时间:2023-10-29 18:08:12
Python中常见的数据类型转换函数有以下几个:
1. int(x, base=10):将x转换为一个整数。base参数用于指定x的进制,默认为10进制。示例用法:
num = int("10")
print(num) # 输出:10
num = int("101", base=2)
print(num) # 输出:5
2. float(x):将x转换为一个浮点数。示例用法:
num = float("3.14")
print(num) # 输出:3.14
3. str(x):将x转换为一个字符串。示例用法:
num = str(10) print(num) # 输出:"10"
4. list(x):将x转换为一个列表。示例用法:
items = list("hello")
print(items) # 输出:['h', 'e', 'l', 'l', 'o']
5. tuple(x):将x转换为一个元组。示例用法:
items = tuple(["apple", "banana", "orange"])
print(items) # 输出:('apple', 'banana', 'orange')
6. set(x):将x转换为一个集合。示例用法:
items = set([1, 2, 3, 2])
print(items) # 输出:{1, 2, 3}
7. dict(x):将x转换为一个字典。x可以是一个包含键值对的序列对象,或包含两个元素的子序列对象。示例用法:
items = dict([('apple', 1), ('banana', 2), ('orange', 3)])
print(items) # 输出:{'apple': 1, 'banana': 2, 'orange': 3}
items = dict(apple=1, banana=2, orange=3)
print(items) # 输出:{'apple': 1, 'banana': 2, 'orange': 3}
8. eval(x):将x作为一个表达式进行求值并返回结果。示例用法:
result = eval("2 + 3")
print(result) # 输出:5
以上是常见的数据类型转换函数及其用法。根据具体需求,可以选择适当的转换函数来将一个数据类型转换为另一个数据类型。
