For Python programming language, you do not need to declare the type of a variable before using it, but in some specific scenario, type conversion is still required. For example, if you want to use the print() function to generate the output of the information “your weight:” and the weight value with floating-point type, the following code is executed:
weight = 60.0 print("Your weight is" + weight)
The output is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
(ipython-input-84-9448d266793e) in (module)
----> 1 print("Your weight is" + weight)
TypeError: can only concatenate str (not "float") to str
You will find that this is wrong. The interpreter prompts us that strings and floating-point variables cannot be directly connected. You need to convert the floating-point variable weight to a string in advance.
Fortunately, Python has provided us with several functions that can perform data type conversions, as shown in table below.
Python codes | Explanations |
---|---|
int(x) | Convert x to integer type |
float(x) | Convert x to floating point type |
complex(real, [image]j) | Create a complex type |
str(x) | Convert x to string |
repr(x) | Convert x to expression string |
eval(str) | Evaluates a valid Python expression in a string and returns an object |
chr(x) | Convert integer x to one character |
ord(x) | Convert a character x to its corresponding integer value |
hex(x) | Convert an integer x to a hexadecimal string |
oct(x) | Converts an integer x to an octal string |
It should be noted that when using a 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:
For example:
int ("123") #Conversion succeeded 123 int ("123a") #Conversion failed
The output is:
123
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
(ipython-input-86-3b34fbb4728d) in (module)
----> 1 int("123a")
ValueError: invalid literal for int() with base 10: '123a'
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises