Converting String to int in Python
In Python, you may convert an int to a string in different ways. For example:
- str() Function
- format() Method
- f-string
- join() function- For list of int
In this tutorial, we will show you examples of a few ways.
The str function in Python
The str function of Python can be used to convert an integer to a string.
The str() function takes an object, that can be an int type value, and it returns the string version of that object.
First, have a look at how the str() function is used.
Syntax of Python str() function
Following is the syntax of using the str() function for converting an object into a string:
e.g.
str (123)
or str (int_variable)
An example of converting an int value to a string
In this example, an int variable is assigned a value.
After that, the str() function is used to convert this into string, and the print function is used to display it with a string variable. See the demo and code online:
The code:
str_x = "A string to int conversion:" a = 123 print (str_x, str(a))
Output:
Using int variable in concatenation example
If you try using the int variable or value in concatenation with a string, it will generate an error. For example, this code will generate an error:
The code:
str_x = "A string to int conversion demo:" a = 123 print (str_x + a)
Result:
By converting the int variable to a string, after using the str() function, the error will not be generated. See the same example as above, this time with str function:
str_x = "A string to int conversion demo:" a = 123 print (str_x + str(a))
Result:
A string to int conversion demo: 123>>>
No error is generated, as you can see in the output above.
An example of format() method for int to string
The example below shows converting an int to string by format method.
The code:
a_int = 10 str_int = "{}".format(a_int) print (str_int) print("The type of object is: ", type(str_int))
Output:
The type of object is: <class ‘str’>
You can see that we used Python type function and it returned <class ‘str’>.
Using the f-string example
See the example below of using f-string for converting the int to string:
num = 20 str_int = f"{num}" print (str_int) print("Type of num: ", type(num)) print("Type of str_int ", type(str_int))
Output:
Type of num: <class ‘int’>
Type of str_int <class ‘str’>
For clarity, we displayed the types of num as well as str_int variable to confirm it has connected to the string type.