# 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.
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.
str(value)
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'
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 "main.py", 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'
value = 400
result = f'{value}'
# -> '400'
0 Comments