Convert int to string Python is not the same as other programming languages. Like Java and other language provide typecasting but python doesn’t implicitly typecast integer or float or numbers to strings in the condition of concatenating with strings.
Because a python number exists in the place of the integer so this topic can be called “Convert number to string Python”.
Python has a
str() built-in function which will convert the argument passed into a string format.
Where str() is built-in function and int_value is an integer value, which you want to convert into strings.
Right Way Convert int to string Python
This example of when you want to concatenate with strings.
age = 18 print("Hello, My age is " + str(age) + " years old")
Output: Hello, I am 18 years old
Another example converts only int or number into strings.
num = 18 print('Before ', type(num)) # converting int to string str_value = str(num) print('After ', type(str_value))
Output: Before <class ‘int’>
After <class ‘str’>
Wrong-Way convert int to string – Don’t Do
It can be interview question, must read all tutorial how to convert an integer to string in python.
age = 18 print("Hello, My age is " + age + " years old")
TypeError: can only concatenate str (not "int") to str
Do comment if you have any questions on this topic.
Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Convert int to string examples are in Python 3, so it may change its different from python 2 or upgraded versions.