10-Data type conversion
1: Why data type conversion is needed
- Splice data of different data types together.
Two: str()
-
Function: Convert other data types to strings (str).
-
str( ) The converted data is only temporarily converted and will not be permanently converted. int( ), float( )< a i=3>Similarly.
-
Demo:
s1 = 'nb' n1 = 1234 f1 = 3.14 b1 = True print(s1,type(s1),n1,type(n1),f1,type(f1),b1,type(b1)) print(str(s1),type(str(s1)),str(n1),type(str(n1)),str(f1),type(str(f1)),str(b1),type(str(b1))) print(s1,type(s1),n1,type(n1),f1,type(f1),b1,type(b1))
Output:
nb <class 'str'> 1234 <class 'int'> 3.14 <class 'float'> True <class 'bool'> nb <class 'str'> 1234 <class 'str'> 3.14 <class 'str'> True <class 'str'> nb <class 'str'> 1234 <class 'int'> 3.14 <class 'float'> True <class 'bool'>
Three: int()
-
Function: Convert other data types to integers (int)
-
Also a temporary conversion
-
When converting str type to int type, the string of str must be an integer string, otherwise an error will be reported.
-
Demo:
s2 = '324' n2 = 234 f2 = 8.5 b2 = False print(s2,type(s2),n2,type(n2),f2,type(f2),b2,type(b2)) print(int(s2),type(int(s2)),int(n2),type(int(n2)),int(f2),type(int(f2)),int(b2),type(int(b2))) print(s2,type(s2),n2,type(n2),f2,type(f2),b2,type(b2))
Output:
324 <class 'str'> 234 <class 'int'> 8.5 <class 'float'> False <class 'bool'> 324 <class 'int'> 234 <class 'int'> 8 <class 'int'> 0 <class 'int'> 324 <class 'str'> 234 <class 'int'> 8.5 <class 'float'> False <class 'bool'>
Four: float()
-
Function: Convert other data types to floating point types (float)
-
Also a temporary conversion
-
When converting a str type value, it must be a numeric string (integer/floating point number). If it is an integer, ".0" will be added at the end, and floating point numbers will be converted directly.
-
When converting a Boolean value, 1.0 if True and 0.0 if False
-
Demo:
s3 = '52' n3 = 89 f3 = 52.2 b3 = False print(s3,type(s3),n3,type(n3),f3,type(f3),b3,type(b3)) print(float(s3),type(float(s3)),float(n3),type(float(n3)),float(f3),type(float(f3)),float(b3),type(float(b3))) print(s3,type(s3),n3,type(n3),f3,type(f3),b3,type(b3))
Output:
52 <class 'str'> 89 <class 'int'> 52.2 <class 'float'> False <class 'bool'> 52.0 <class 'float'> 89.0 <class 'float'> 52.2 <class 'float'> 0.0 <class 'float'> 52 <class 'str'> 89 <class 'int'> 52.2 <class 'float'> False <class 'bool'>
expand:
-
Data of type int and type str cannot be connected using the connector "+", and data type conversion is required.
-
Note:
-
Single line comments
# 这是单行注释
-
Multi-line comments
''' 多行注释 多行注释 '''
-
Chinese encoding declaration comments
-
Add a Chinese declaration comment at the beginning of the file to specify the encoding format of the source code file.
-
Demo:
#coding: gbk
-
-