Home >Backend Development >Python Tutorial >An in-depth analysis of Python's data type conversion functions and usage examples
Detailed explanation of Python data type conversion function and usage examples
In Python programming, data type conversion is a very common operation. When we deal with different types of data, we need to convert it into the appropriate type for manipulation or comparison. Python provides a series of data type conversion functions that can easily convert between data types. This article will introduce various data type conversion functions in Python in detail and provide usage examples.
Example 1: Convert a number to an integer type
num = 10.5 num_int = int(num) print(num_int) # 输出:10
Example 2: Convert a string to an integer type
str_num = "20" str_num_int = int(str_num) print(str_num_int) # 输出:20
Example 1: Convert a number to a floating point type
num_int = 10 num_float = float(num_int) print(num_float) # 输出:10.0
Example 2: Convert a string to a floating point type
str_num = "3.14" str_num_float = float(str_num) print(str_num_float) # 输出:3.14
Example 1: Convert integer to string
num_int = 10 num_str = str(num_int) print(num_str) # 输出:"10"
Example 2: Convert floating point to string
num_float = 3.14 num_str = str(num_float) print(num_str) # 输出:"3.14"
Example 1: Convert integer to Boolean value
num_int = 0 num_bool = bool(num_int) print(num_bool) # 输出:False
Example 2: Convert string to Boolean value
str_empty = "" str_bool = bool(str_empty) print(str_bool) # 输出:False str_nonempty = "nonempty" str_bool = bool(str_nonempty) print(str_bool) # 输出:True
Example 1: Convert string to list
str_word = "hello" str_list = list(str_word) print(str_list) # 输出:['h', 'e', 'l', 'l', 'o']
Example 2: Convert tuple to list
tuple_nums = (1, 2, 3) tuple_list = list(tuple_nums) print(tuple_list) # 输出:[1, 2, 3]
list_nums = [1, 2, 3] list_tuple = tuple(list_nums) print(list_tuple) # 输出:(1, 2, 3)Example 2: Convert string to tuple
str_word = "hello" str_tuple = tuple(str_word) print(str_tuple) # 输出:('h', 'e', 'l', 'l', 'o')
list_nums = [1, 2, 2, 3, 3, 3] list_set = set(list_nums) print(list_set) # 输出:{1, 2, 3}
Example 2: Convert a string to a set
str_word = "hello" str_set = set(str_word) print(str_set) # 输出:{'e', 'o', 'l', 'h'}
Through the introduction of this article, we have learned about Python Common data type conversion functions and usage examples are provided. In actual programming, by using these functions flexibly as needed, conversion between different data types can be easily achieved.
The above is the detailed content of An in-depth analysis of Python's data type conversion functions and usage examples. For more information, please follow other related articles on the PHP Chinese website!