Python String to Int and Int to String: In Python, you can directly convert one data type into another. In this article, you will learn to convert String to Integer and Integer to String.
During your programming or software development journey, you will need to convert one data type into another.
For example – While reading numeric data from another file, the data will be in String format. So, you have to explicitly convert it into Integer type to perform mathematical operations on that data.
So, today we will take a deep look at different methods which you can use to convert String to Integer data type and Integer to String data type.
However, first let’s see the different ways to store or represent Integer in Python.
Table of Contents
Representing Integer using str and int
In Python, you can store Integer value using different data types. Some of the most common data types used to store Integer are str and int.
For example – You can represent integer value 150 using String literal in Python as follow:
s_value = “150”
Similarly, To represent integer value 150 using Integer literal in Python. Use the following code.
i_value = 150
Now, these are the Decimal representation of the Integer value.
Similarly, there are other Number System available, like – Binary Number System, Octal Number System and Hexadecimal Number System.
In Python, you can easily represent the Integer in these Number System by using prefix.
You have to add some specific prefix to represent these Number System in Integer.
For example – To represent Binary value(10010110) in Integer(106), add “0b” prefix.
b_value = 0b1101010
To represent Octal value(226) in Integer(106), add “0o” prefix.
o_value = 0o152
Similarly, to represent Hexadecimal Value(6A) in Integer(106), add “0x” prefix.
h_value = 0x6A
You can also represent these Values in String literal by using quote(” “) symbol.