Although Python is a weakly typed programming language and does not need to declare the type of a variable before using it like Java or C language, type conversion is still needed in some specific scenarios.
For example, we want to output the information "Your height:" and the value of the floating point type height by using the print() function. If the following code is executed in the interactive interpreter:
>>> height = 70.0
>>> print("Your height"+height)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print("Your height" +height)
TypeError: must be str, not float
You will find that this is wrong. The interpreter prompts us that strings and floating-point type variables cannot be directly connected. The floating-point type variable height needs to be converted to a string in advance.
Fortunately, Python has provided us with a variety of functions that can achieve data type conversion, as shown in Table 1.
function | effect |
---|---|
int(x) | Convert x to integer type |
float(x) | Convert x to floating point type |
complex(real,[,imag]) | create a plural |
str(x) | Convert x to string |
repr(x) | Convert x to an expression string |
eval(str) | Evaluates a valid Python expression in a string and returns an object |
chr(x) | Convert integer x to a character |
ord(x) | Convert a character x to its corresponding integer value |
hex(x) | Convert an integer x to a hexadecimal string |
oct(x) | Convert an integer x to an octal string |
It should be noted that when using the type conversion function, the data provided to it must be meaningful. For example, the int() function cannot convert a non-numeric string to an integer:
>>> int("123") #Conversion successful
123
>>> int("123") #Conversion failed
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
int("123")
ValueError: invalid literal for int() with base 10: '123'
>>>