Home > Article > Backend Development > Introducing common Python data type conversion functions
Introduction to commonly used data type conversion functions in Python
In the Python programming language, data type conversion is a common and important operation. Through data type conversion, we can convert a data object from one type to another, allowing us to process different types of data more flexibly. This article will introduce commonly used data type conversion functions in Python and provide specific code examples.
Sample code:
num1 = "10" num2 = 3.5 num3 = 7.8 result1 = int(num1) result2 = int(num2) result3 = int(num3) print(result1) # 输出结果为 10 print(result2) # 输出结果为 3 print(result3) # 输出结果为 7
Sample code:
num1 = 10 num2 = "3.5" num3 = "7.8" result1 = float(num1) result2 = float(num2) result3 = float(num3) print(result1) # 输出结果为 10.0 print(result2) # 输出结果为 3.5 print(result3) # 输出结果为 7.8
Sample code:
num1 = 10 num2 = 3.5 result1 = str(num1) result2 = str(num2) print(result1) # 输出结果为 "10" print(result2) # 输出结果为 "3.5"
Sample code:
str1 = "Hello, World!" tuple1 = (1, 2, 3, 4, 5) set1 = {1, 2, 3, 4, 5} result1 = list(str1) result2 = list(tuple1) result3 = list(set1) print(result1) # 输出结果为 ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'] print(result2) # 输出结果为 [1, 2, 3, 4, 5] print(result3) # 输出结果为 [1, 2, 3, 4, 5]
Sample code:
str1 = "Hello, World!" list1 = [1, 2, 3, 4, 5] set1 = {1, 2, 3, 4, 5} result1 = tuple(str1) result2 = tuple(list1) result3 = tuple(set1) print(result1) # 输出结果为 ('H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!') print(result2) # 输出结果为 (1, 2, 3, 4, 5) print(result3) # 输出结果为 (1, 2, 3, 4, 5)
Summary:
This article introduces commonly used data type conversion functions in Python and their specific code examples. By using these functions, we can flexibly convert between different types of data and adapt the data to the data type we need. Mastering the use of these functions is of great help in daily programming work.
The above is the detailed content of Introducing common Python data type conversion functions. For more information, please follow other related articles on the PHP Chinese website!