【发布时间】:2010-10-31 23:45:31
【问题描述】:
我想在 Python 中将整数转换为字符串。我徒劳地打字:
d = 15
d.str()
当我尝试将其转换为字符串时,它会显示一个错误,例如 int 没有任何名为 str 的属性。
【问题讨论】:
-
对于这些类型的转换,一个好的解决方案是使用像converttypes.com 这样的网站,您可以在其中查看几乎所有编程语言的所有转换。
我想在 Python 中将整数转换为字符串。我徒劳地打字:
d = 15
d.str()
当我尝试将其转换为字符串时,它会显示一个错误,例如 int 没有任何名为 str 的属性。
【问题讨论】:
试试这个:
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
【讨论】:
Python 中没有类型转换和类型强制。您必须以显式方式转换您的变量。
要转换字符串中的对象,请使用str() 函数。它适用于任何定义了名为__str__() 的方法的对象。其实
str(a)
等价于
a.__str__()
如果您想将某些内容转换为 int、float 等,则相同。
【讨论】:
管理非整数输入:
number = raw_input()
try:
value = int(number)
except ValueError:
value = 0
【讨论】:
我认为最体面的方式是``。
i = 32 --> `i` == '32'
【讨论】:
repr(i),所以对于longs会很奇怪。 (试试i = `2 ** 32`; print i)
您可以使用%s 或.format:
>>> "%s" % 10
'10'
>>>
或者:
>>> '{}'.format(10)
'10'
>>>
【讨论】:
对于想要将 int 转换为特定数字的字符串的人,建议使用以下方法。
month = "{0:04d}".format(localtime[1])
更多细节可以参考 Stack Overflow 问题Display number with leading zeros。
【讨论】:
在 Python => 3.6 中,您可以使用f 格式:
>>> int_value = 10
>>> f'{int_value}'
'10'
>>>
【讨论】:
随着f-strings 在 Python 3.6 中的引入,这也将起作用:
f'{10}' == '10'
它实际上比调用str() 更快,但以可读性为代价。
其实比%x字符串格式化和.format()快!
【讨论】:
对于 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'>
更详细的答案可以查看这篇文章:Converting Python Int to String and Python String to Int
【讨论】:
这是一个更简单的解决方案:
one = "1"
print(int(one))
>>> 1
在上面的程序中,int()用来转换一个整数的字符串表示形式。
注意:字符串格式的变量只有在变量完全由数字组成时才能转换为整数。
同理,str()用于将整数转换为字符串。
number = 123567
a = []
a.append(str(number))
print(a)
我使用了一个列表来打印输出以突出显示变量 (a) 是一个字符串。
>>> ["123567"]
但要了解列表存储字符串和整数的区别,请先查看以下代码,然后再查看输出。
a = "This is a string and next is an integer"
listone=[a, 23]
print(listone)
>>> ["This is a string and next is an integer", 23]
【讨论】:
在python中有几种方法可以将整数转换为字符串。 您可以使用 [ str(integer here) ] 函数、f-string [ f'{integer here}']、.format()function [ '{}'.format(integer here) 甚至 '%s' % 关键字 [此处为 '%s'% 整数]。所有这些方法都可以将整数转换为字符串。
见下例
#Examples of converting an intger to string
#Using the str() function
number = 1
convert_to_string = str(number)
print(type(convert_to_string)) # output (<class 'str'>)
#Using the f-string
number = 1
convert_to_string = f'{number}'
print(type(convert_to_string)) # output (<class 'str'>)
#Using the {}'.format() function
number = 1
convert_to_string = '{}'.format(number)
print(type(convert_to_string)) # output (<class 'str'>)
#Using the '% s '% keyword
number = 1
convert_to_string = '% s '% number
print(type(convert_to_string)) # output (<class 'str'>)
【讨论】: