Integer to String conversion in Python

If you are a Python programmer, then you must be aware of the syntax for converting integer values to strings. In this code snippet, We will tell you how to convert integers to strings in Python programmatically.

# Using str() method
int_val = 10
strVal = str(int_val)

# OR use __str__()
str2 = int_val.__str__()

The inbuilt function of python - str() can convert any data type to string. So if you want to convert an integer value to a string you can use this function.

Python str() method

The python str() method is primarily used to convert an integer type value to a string. The basic syntax of this method is as below.


Here, value is a required parameter that will be converted to a string. Here are more examples of the str() method.

result1 = str(30)
# -> '30'

result2 = str(100)
# -> '100'

result3 = str("NaN")
# -> 'NaN'

Why do we convert integer to string?

There are a lot of use cases of converting an integer to a string. One of them is to concatenate or merge integers and strings. If you add an integer and a string it will throw an error. We can understand it using the below example.

val = 20
print(val + " apples")

The above code will throw an exception as we are trying to add or merge one integer and one string. The exceptions details are as below

Traceback (most recent call last):
  File "", line 3, in <module>
    print(val +" apples")
TypeError: unsupported operand type(s) for +: 'int' and 'str'The 

The above exception will occur if we will add the integer value to the string without converting it to a string. So if we want to add them we can use the below code.

val = 20

print(str(val) +" apples")
# -> 20 apples

The above code will output 20 apples without throwing an exception.

There are more methods that can be used to convert an integer to a string. We will describe them below one by one.

value = 300

result = "{}".format(value)

# -> '300'
We can use the format() function in python to convert an int type value to a string. In the above code, we have a variable value that contains a integer value. We are using the format() function and passing our integer value to it. The result variable contains the string format value.
value = 400

result = f'{value}'

# -> '400'
f-string is a powerful python feature to define string templates and execute them. For instance, if you want to convert the integer 400 into string format vale, nyou can do that using f-string.
Was this helpful?