Register Login

Converting Python Integer to String

Updated Mar 18, 2020

How to Convert Python int to string?

In python, the python interpreter does not implicitly convert integer to string value. To convert an integer to string value explicitly we have various methods. Which we will discuss further.

When we try to concatenate an integer to string value it throws an error TypeError: can only concatenate str (not "int") to str. Let us try to understand the error and its solutions with the help of a few examples.

Example:

age = 15
print("Hello world, my age is "+ age)

Output:

File "age.py", line 2, in <module>

    print("Hello world, my age is "+ age)

TypeError: can only concatenate str (not "int") to str

Explanation

In the above example, age is defined as an integer variable. In the 2nd line of the code, we concatenating an integer value to a string. But, the python interpreter does not implicitly convert an integer to string value. Thus the TypeError is encountered.       

1) Converting Integer to String Using Built-in Function str()

Example

age = 15
print("Hello world, my age is "+ str(age))

Output

Hello world, my age is 15

Explanation

In the above solution, we used built-in str() function to convert ‘age’ to a string. And then concatenated it to the rest of the string. Thus no error is encountered.

2) Converting Integer to String Using Special Method __str__()

 When we use the built-in function str() it automatically invokes a special method __str__(). Instead of using “str(object)” we can use “object.__str__()”.

Example

age = 15
print("Hello world, my age is "+ age.__str__())

Output

Hello world, my age is 15

Explanation

In the above solution, we used the special method __str__() to convert an integer to string value.

3) Using f-string for String Formatting

Example

name="Arthur"
age=19
print( f"Hello world My name is {name} and i'm {age} years old")

Output

Hello world My name is Arthur and i'm 19 years old

Note: This solution works with Python 3

Explanation

In the above example, we used f-string for formatting. f-strings consist of 2 parts one is the character ‘f’ ( ‘f’ can either be lower case or upper case). And other is the string enclosed within single, double or triple quotes that we want to format.

Conclusion

Unlike many other languages, Python does not automatically convert an integer to string, while concatenating them with strings. If we try to do so a TypeError is raised. So to concatenate an integer value to string value, we have to explicitly convert them into a string. And above we have discussed the various method to do so.


×