Home > Article > Backend Development > Quickly master Python data type conversion functions
Quickly master the data type conversion function in Python, specific code examples are required
Python is an easy-to-learn and use programming language that provides rich data Type conversion functions can help us quickly convert between different data types. In this article, we will take a deep dive into data type conversion functions in Python and provide concrete code examples.
Code example:
num_str = "123" num_int = int(num_str) print(num_int) # 输出:123 print(type(num_int)) # 输出:<class 'int'>
Code example:
num_str = "3.14" num_float = float(num_str) print(num_float) # 输出:3.14 print(type(num_float)) # 输出:<class 'float'>
Code example:
num_int = 123 num_str = str(num_int) print(num_str) # 输出:"123" print(type(num_str)) # 输出:<class 'str'>
Code example:
num_str = "123" num_list = list(num_str) print(num_list) # 输出:['1', '2', '3'] print(type(num_list)) # 输出:<class 'list'>
Code example:
num_str = "123" num_tuple = tuple(num_str) print(num_tuple) # 输出:('1', '2', '3') print(type(num_tuple)) # 输出:<class 'tuple'>
Code example:
num_list = [1, 2, 2, 3] num_set = set(num_list) print(num_set) # 输出:{1, 2, 3} print(type(num_set)) # 输出:<class 'set'>
Code example:
num_list = [[1, '一'], [2, '二'], [3, '三']] num_dict = dict(num_list) print(num_dict) # 输出:{1: '一', 2: '二', 3: '三'} print(type(num_dict)) # 输出:<class 'dict'>
The above are the commonly used data type conversion functions in Python. By using these functions, we can flexibly convert between different data types. Mastering these functions will bring great convenience to your programming work. I hope the sample code in this article can help you better understand and use these functions.
The above is the detailed content of Quickly master Python data type conversion functions. For more information, please follow other related articles on the PHP Chinese website!