Python learning practices ------ conversion of basic data types and python learning practices
In Python2, the basic data types are bool, int, float, str, list, tuple, dict, and set. It can be viewed through int. _ class _. Other analogy
At the same time, they can also perform data type conversion, because they are also classes, and an Instance Object of the class is created during the conversion.
Convert to bool: bool (23)-> True;
Bool ('')-> True;
Bool ('')-> False;
Bool (0)-> False;
Bool ('0')-> True;
Bool (None)-> False;
Convert to an integer: int (12.8)-> 12;
Int ('12')-> 12;
Int ('12. 8')-> ValueError: invalid literal for int () with base 10: '12. 8 ';
Int ('A')-> ValueError: invalid literal for int () with base 10: 'A'
Convert to floating point: float ('23. 5')-> 23.5;
Float ('23')-& gt; 23.0;
Float (23)-& gt; 23.0
Float ('A')-> ValueError: cocould not convert string to float:
Convert to string: str (23)-> '23'
Str (23.9)-> '23. 9'
Str ([, 54])-> '[, 54]'
Tuples, dictionaries, and the same as above, are both enclosed in quotation marks and converted to strings.
Str ({2, 3, 4})-> 'set ([2, 3, 4])'
Convert to list: list ()-> Create an empty list []
List (23)-> TypeError: 'int' object is not iterable
List ('abc')-> ['A', 'B', 'C']
List ('A', 'B', 'C')-> ['A', 'B', 'C']
List ({'A': 'A', 'B': 'B', 'C': 'C'})-> ['A', 'C ', 'B']
List ({'A', 'B', 12,23})-> ['A', 'B', 12, 23]
Convert to tuples: tuple ()-> Create an empty tuples
The tuple () parameter must be an iterable object. Refer to the list conversion above
Convert to dictionary: help (dict ):
Dict ()-> new empty dictionary
Dict (mapping)-> new dictionary initialized from a mapping object's(Key, value) pairs
Dict (iterable)-> new dictionary initialized as if:
D = {}
For k, v in iterable:
D [k] = v
Dict (** kwargs)-> new dictionary initialized with the name = value pairs in the keyword argument list. For example:
Dict (one = 1, two = 2)-> {'two': 2, 'one': 1}
Dict ([{1, 2}, {3, 4}])->{1: 2, 3: 4}
Dict ([('A', 'A'), ('B', 'B')])-> {'A': 'A', 'B ': 'B '}
Dict ([[1, 2], [3, 4])-> {1: 2, 3: 4}
Dict ('A', 1), ('B', 2), ('C', 3)-> {'A': 1, 'C': 3, 'B': 2}
Dict ({1, 2}, {3, 4})-> {1: 2, 3: 4}
Dict ([1, 2], [3, 4], ['A', 'a'])-> {'A': 'A', 1: 2, 3: 4}
Dict ({(2, 3), (4, 5)})->{2: 3, 4: 5}
Convert to a set: set ()-> set ([])
Set ('abc')-> set (['A', 'C', 'B'])
Set ([1, 23, 4])-> set ([1, 4, 23])
Set ({,})-> set ([1, 3])
Set ({1, 2, 3, 4})-> set ([1, 2, 3, 4])