尝试 my_int.str()
会出错,提示 int
没有任何名为 str
的属性。
尝试这个:
str(i)
Python 中没有类型转换和类型强制。您必须以显式方式转换变量。
要将对象转换为字符串,请使用 str()
函数。它适用于任何定义了名为 __str__()
的方法的对象。实际上
str(a)
相当于
a.__str__()
如果要将某些内容转换为 int
、float
等,则相同。
管理非整数输入:
number = raw_input()
try:
value = int(number)
except ValueError:
value = 0
>>> 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 => 3.6 可以使用f
格式:
>>> int_value = 10
>>> f'{int_value}'
'10'
>>>
对于 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
我认为最体面的方式是``。
i = 32 --> `i` == '32'
repr(i)
,因此对于 long 来说会很奇怪。 (试试 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-strings 的引入,这也将起作用:
f'{10}' == '10'
它实际上比调用 str()
更快,但以可读性为代价。
事实上,它比 %x
字符串格式化和 .format()
更快!
在 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'>)
这是一个更简单的解决方案:
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]
不定期副业成功案例分享