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:
# code # gfg contains string 10 gfg = "10"
# using the int(), string is auto converted to int print ( int (gfg) + 20 )
|
30
Example 2: Converting a Python String to float:
# code gfg = "10"
# float(gfg) gives 10.0 print ( float (gfg) + 2.0 )
|
12.0
Example 3: Converting a Python int to a String:
This is achieved by using str() function as shown below
# code gfg = 100
# str(gfg) gives '100' print ( str (gfg) + " is a 3 digit number" )
# concatenation is performed between them print ( str (gfg) + "200" )
|
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
# 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" )
|
20.0is now a string 20.030.0
Example 5: Converting python int to string using format() function
# python program to convert integer number # to string using format() function intnum = 20
print ( "string is {} " . format (intnum))
print ( type ( "string is {} " . format (intnum)))
|
string is 20 <class 'str'>
Example 5: Converting python float to string using format() function
# 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)))
|
string is 20.0 <class 'str'>
Example 6: Converting python string to int using eval() function
# converting python string to # int using eval() function a = "100"
print ( eval (a) + 12 )
|
112
Example 7: Converting python string to float using eval() function
# converting python string to # float using eval() function a = "100.00"
print ( eval (a) + 12 )
|
112.0