Convert Strings to Numbers and Numbers to Strings in Python
Last Updated :
12 Jan, 2023
In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let’s see how to use each of them.
Example 1: Converting a Python String to an int:
Python3
gfg = "10"
print ( int (gfg) + 20 )
|
Example 2: Converting a Python String to float:
Python3
gfg = "10"
print ( float (gfg) + 2.0 )
|
Example 3: Converting a Python int to a String:
This is achieved by using str() function as shown below
Python3
gfg = 100
print ( str (gfg) + " is a 3 digit number" )
print ( str (gfg) + "200" )
|
Output
100 is a 3 digit number
100200
Example 4: Converting a Python float to a String
This is achieved by using str() function as shown below
Python3
gfg = 20.0
print ( str (gfg) + "is now a string" )
print ( str (gfg) + "30.0" )
|
Output
20.0is now a string
20.030.0
Example 5: Converting python int to string using format() function
Python3
intnum = 20
print ( "string is {} " . format (intnum))
print ( type ( "string is {} " . format (intnum)))
|
Output
string is 20
<class 'str'>
Example 5: Converting python float to string using format() function
Python3
floatnum = 20.00
print ( "string is {} " . format (floatnum))
print ( type ( "string is {} " . format (floatnum)))
|
Output
string is 20.0
<class 'str'>
Example 6: Converting python string to int using eval() function
Python3
a = "100"
print ( eval (a) + 12 )
|
Example 7: Converting python string to float using eval() function
Python3
a = "100.00"
print ( eval (a) + 12 )
|
Please Login to comment...