Advertisement
Advertisement


Converting integer to string in Python


Question

I want to convert an integer to a string in Python. I am typecasting it in vain:

d = 15
d.str()

When I try to convert it to string, it's showing an error like int doesn't have any attribute called str.

2020/08/18
1
1387
8/18/2020 12:22:01 PM

Accepted Answer

>>> str(10)
'10'
>>> int('10')
10

Links to the documentation:

Conversion to a string is done with the builtin str() function, which basically calls the __str__() method of its parameter.

2020/06/04
2129
6/4/2020 2:26:33 PM

Try this:

str(i)
2009/06/07

There is not typecast and no type coercion in Python. You have to convert your variable in an explicit way.

To convert an object in string you use the str() function. It works with any object that has a method called __str__() defined. In fact

str(a)

is equivalent to

a.__str__()

The same if you want to convert something to int, float, etc.

2017/05/27

To manage non-integer inputs:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0
2019/06/23

>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5
2018/05/22

In Python => 3.6 you can use f formatting:

>>> int_value = 10
>>> f'{int_value}'
'10'
>>>
2018/07/27

Source: https://stackoverflow.com/questions/961632
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]