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" ) # concatination 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 float() 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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.