我想在Python中把一个整数转换成一个字符串。我正在进行类型化处理,但这是徒劳的。
d = 15
d.str()
当我试图将其转换为字符串时,它显示了一个错误,如int
没有任何名为str
的属性。
在Python中没有类型转换,也没有类型强制。 你必须以一种显式的方式转换你的变量。
要将一个对象转换为字符串,你需要使用str()
函数。
它适用于任何定义了名为"str()`方法的对象。
事实上
str(a)
相当于
a.__str__()
如果你想把某个东西转换为int、float等,也是一样的。
>>> 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
对于想把int转换成特定数字的字符串的人,推荐使用下面的方法。
month = "{0:04d}".format(localtime[1])
详情可以参考Stack Overflow问题https://stackoverflow.com/questions/134934/display-number-with-leading-zeros。
在Python 3.6中,你可以使用f-strings新特性来转换为字符串,而且它比str()函数更快,它就是这样使用的。
age = 45
strAge = f'{age}'
Python 为此提供了 str() 函数。
digit = 10
print(type(digit)) # will show <class 'int'>
convertedDigit= str(digit)
print(type(convertedDigit)) # will show <class 'str'>
更详细的解答你可以看看这篇文章。 [将Python Int转换为String和Python String转换为Int][1] 。
[1]: https://www.ninjadevcorner.com/2019/06/converting-python-int-to-string-python-string-to-int.html