How To Convert Python String to Int and Int to String
Sometimes we may need to convert a variable of type String to Integer and from Integer to String.
Python provides a built-in method to do this exercise. The methods are int()
to convert String to Integer and str()
to convert Integer to String.
- int() methond to convert String to Integer
- str() method to convert Integer to String
int() method
int(string, base)
All values passed by a parameter in int () method are by default of base 10. But we can change the base according to the needs.
Let’s take number 3 as an example.
First, let’s initialize a variable and assign with value 3 inside quotes.
number = '3'
print(number)
output
'3'
In this case, we don’t need to check the data type because we know that in Python everything in quotes are strings.
To convert number to integer, we must put its variable as a parameter in int() method.
int(number)
We will allocate the result of the method in the same variable
number = int(number)
Now we can use the number value to perform calculations
compiled code
number = '3'
number = int(number)
print(number)
output
3
We can change the decimal base to binary base.
We know that 3 in binary is 11.
For that we must explicitly place the base in the int () method
number = '11'
number = int(number, 2)
print(number)
output
3
str() method
str(object, encoding=encoding, errors=errors)
object – Any object. Specifies the object to convert into a string
encoding – The encoding of the object. Default is UTF-8
errors – Specifies what to do if the decoding fails
To convert integer to string is very easy and simple with the str() method. Just passing the value that we want convert as a method parameter.
number = 3
number = str(number)
print(number)
output
'3'
As you can see, it is simple to convert string to integer and integer to string. I hope that you enjoyed it.