Python coercion summary
coercion
Each data type in python has a corresponding method that can convert the data type
Without further ado, let's take a picture:
- str() can convert all other data types to string types
f_num = 3.1415 print ( str ( f_num ) )
- 1
- 2
- When int() converts a string to a number type, if the string is a pure number, it can be converted
f_num = 3.1415 str_num = "213" print ( int ( str_num ) ) print ( int ( f_num ) ) ''' 213 3 '''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- The container type cannot be converted to a numeric int type
- float() The conversion of floating point type is the same as that of int type, but the result of the conversion is a floating point type
- bool() can convert other types to True or False of boolean type
'',0,0.0,False,[],{},(),set()
The result of converting to bool in these cases is False
- list() list
- Number types are non-container types and cannot be converted to lists
- Converting a string to a list treats each character in the string as an element of the list
str_num = "213" print ( list ( str_num ) ) #['2', '1', '3']
- 1
- 2
- 3
- Collection can be converted to list type
- Tuples can be converted to list type
- A dictionary can be converted to a list list type, only the keys in the dictionary are retained
- tuple() tuple
- Same as the cast rules for lists
- set() collection
- The numeric type is not a container type and cannot be converted to a collection
- Strings, lists, tuples can be converted to sets and the result is unordered
- When a dictionary is converted to a set, only the key of the dictionary is retained
- dict() dictionary
- The numeric type is not a container type and cannot be converted to a dictionary
- Strings cannot be directly converted to dictionaries
- The list can be converted to a dictionary, the requirement is a second-level list, and each second-level element can only have two values
- Tuples can be converted to dictionaries, the requirement is a second-level tuple, and each second-level element can only have two values
str_dict = '{"ywh":21}' print ( eval ( str_dict ) ) # string to dictionary list_dict = [ [ "123" , 2 ] , [ "ywh" , 21 ] ] print ( dict ( list_dict ) ) #List to string #Convert with zip() list_dict = [ 'hello' , 'world' , 'haha' , 31 , 32 , 33 ] print ( dict ( zip ( list_dict [ 0 : : 2 ] , list_dict [ 1 : : 2 ] ) ) ) list1 = [ 'ywh' , 'fish' , 'SF' ] list2 = [ 1 , 2 , 3 ] print ( dict ( zip ( list1 , list2 ) ) )
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
{'ywh': 21} {'123': 2, 'ywh': 21} {'hello': 'world', 'haha': 31, 32: 33} {'ywh': 1, 'fish': 2, 'SF': 3}
- 1
- 2
- 3
- 4