tags:

views:

4209

answers:

5

I want to convert a string into integer in python. I am typecasting it, but in vain please help!!

t=raw_input()
c=[]
for j in range(0,int(t)):
    n=raw_input()
    a=[]
    a,b= (int(i) for i in n.split(' '))
    d=pow(a,b)
    d.str()
    c.append(d[0])
for j in c:
    print j

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

+1  A: 

Try this:

str(i)
Lasse V. Karlsen
+8  A: 
>>> str(10)
'10'
>>> int('10')
10

[Edit]

Links to the documentation:
int()
str()

[Edit]

The problem seems to come from this line: d.str()
Conversion to 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.

Bastien Léonard
A: 
>>> i = 5
>>> s = str(5)
>>> print "Hello, world the number is " + s
Hello, world the number is 5
Andy
+1  A: 

There is not typecast and no type coercion in python. You have to convert your variable in a 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 is if you want to convert something to int, float ect...

Andrea Ambu
+2  A: 

To manage non-integer inputs.

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


Ok, if i take your latest code and rewrite a bit to get it working with python,

t=raw_input()
c=[]
for j in range(0,int(t)):
    n=raw_input()
    a=[]
    a,b= (int(i) for i in n.split(' '))
    d=pow(a,b)
    d2=str(d)
    c.append(d2[0])
for j in c:
    print j

It gives me something like,

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

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

nik