Converting integer to string in Python?

Hick Source

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

d = 15

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



answered 9 years ago Lasse Vågsæther Karlsen #1

Try this:


answered 9 years ago Bastien Léonard #2

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

Links to the documentation:

The problem seems to come from this line: d.str().

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

Also, it shouldn't be necessary to call pow(). Try using the ** operator.

answered 9 years ago maxaposteriori #3

>>> 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

answered 9 years ago Andrea Ambu #4

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


is equivalent to


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

answered 9 years ago nik #5

To manage non-integer inputs:

number = raw_input()
    value = int(number)
except ValueError:
    value = 0

Ok, if I take your latest code and rewrite a bit to get it working with Python:

for j in range(0,int(t)):
    a,b= (int(i) for i in n.split(' '))
for j in c:
    print j

It gives me something like:

>>> 2
>>> 8 2
>>> 2 3

Which is the first characters of the string result pow(a,b). What are we trying to do here?

answered 6 years ago Tarun Gupta #6

a = 2

You can use str(a) which gives you a string object of int(2).

answered 3 years ago Nikolas #7

The most decent way in my opinion is ``.

i = 32   -->    `i` == '32'

answered 10 months ago Vikram S #8

Can use %s or .format

>>> "%s" % 10


>>> '{}'.format(10)

answered 8 months ago Gearon #9

For someone who wants to convert int to string in specific digits, the below method is recommended.

month = "{0:04d}".format(localtime[1])

For more details, you can refer to Stack Overflow question Display number with leading zeros.

answered 3 months ago Vikram S #10

In Python => 3.6 you can use f formatting:

>>> int_value = 10
>>> f'{int_value}'

comments powered by Disqus