Convert Strings to Numbers and Numbers to Strings in Python
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
# code # gfg contains string 10 gfg = "10" # using the int(), string is auto converted to int print ( int (gfg) + 20 ) |
Output
30
Example 2: Converting a Python String to float:
Python3
# code gfg = "10" # float(gfg) gives 10.0 print ( float (gfg) + 2.0 ) |
Output
12.0
Example 3: Converting a Python int to a String:
This is achieved by using str() function as shown below
Python3
# code gfg = 100 # str(gfg) gives '100' print ( str (gfg) + " is a 3 digit number" ) # concatenation is performed between them 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
# code gfg = 20.0 # str(gfg) becomes '20.0' print ( str (gfg) + "is now a string" ) # no addition is performed. concatenated output 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
# python program to convert integer number # to string using format() function 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
# python program to convert float integer number # to string using format() function 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
# converting python string to # int using eval() function a = "100" print ( eval (a) + 12 ) |
Output
112
Example 7: Converting python string to float using eval() function
Python3
# converting python string to # float using eval() function a = "100.00" print ( eval (a) + 12 ) |
Output
112.0
Please Login to comment...