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
.
转载于:https://stackoverflow.com/questions/961632/converting-integer-to-string-in-python
>>> str(10)
'10'
>>> int('10')
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.
Try this:
str(i)
>>> 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
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.
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?
a = 2
You can use str(a)
which gives you a string object of int(2)
.
The most decent way in my opinion is ``.
i = 32 --> `i` == '32'
Can use %s
or .format
>>> "%s" % 10
'10'
>>>
(OR)
>>> '{}'.format(10)
'10'
>>>
对于想要将int转换为特定数字的字符串的人,建议使用以下方法。
month = "{0:04d}".format(localtime[1])
有关更多详细信息,吗可以参考Stack Overflow问题。 显示数字的前导零.
In Python => 3.6 you can use f
formatting:
>>> int_value = 10
>>> f'{int_value}'
'10'
>>>