How to convert Python int to string by str method
The str method in Python
The str method of Python can be used to convert an integer to a string. The str() method takes an object, that can be an int type value, and it returns the string version of that object.
In this tutorial of int to string conversion, I will show you different examples of using this method.
First, have a look at how str method is used.
Syntax of Python str() method
Following is the syntax of using the str() method for converting an object into string:
1 class str(object='')
e.g.
str (123)
or str (int_variable)
Note: As such, the str method takes an object, it can be an integer, float, byte etc. As this chapter is focused in integer conversion, so following examples will address integers only.
An example of converting an int value to a string
In this example, an int variable is assigned a value. After that, the str method is used to convert this into string and print function is used to display it with a string variable. See the demo and code online:
See online demo and code
The code:
1 2 3 4 5 6 7 8 9 |
str_x = "A string to int conversion demo:" a = 123 print (str_x, str(a)) |
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:
See online demo and code
The code:
1 2 3 4 5 6 7 8 9 |
str_x = "A string to int conversion demo:" a = 123 print (str_x + a) |
By converting int variable to a string, after using the str method, the error will not generate. See the same example as above, this time with str method:
See online demo and code
The code with str method:
1 2 3 4 5 6 7 8 9 |
str_x = "A string to int conversion demo:" a = 123 print (str_x + str(a)) |
No error is generated, as you can see the output in the demo page.