Python Tutorial - Type Conversion

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:

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)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises