如何将整数转换为字符串?
42 ⟶ "42"
要进行反向操作,请参阅如何将字符串解析为浮点数或整数?。浮点数可以类似地处理,但由于浮点值不精确,因此处理小数点可能会很棘手。有关更具体的建议,请参阅将浮点数转换为字符串而不进行四舍五入。
如何将整数转换为字符串?
42 ⟶ "42"
要进行反向操作,请参阅如何将字符串解析为浮点数或整数?。浮点数可以类似地处理,但由于浮点值不精确,因此处理小数点可能会很棘手。有关更具体的建议,请参阅将浮点数转换为字符串而不进行四舍五入。
f'{10}' == '10'
实际上,它比调用str()
更快,但可读性较差。
事实上,它比%x
字符串格式化和.format()
都要快!
#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'>)
format()
函数:format(42) # 42 --> '42'
如果你想添加千位分隔符:
num = 123456789
format(num, ",") # '123,456,789'
f"{num:,}"
"{:,}".format(num)
或将浮点数转换为字符串表示
format(num, ",.2f") # '123,456,789.00'
f"{num:,.2f}"
'{:,.2f}'.format(num)
对于“欧洲”分隔符:
format(num, "_.2f").replace('.', ',').replace('_', '.') # '123.456.789,00'
f"{num:_.2f}".replace('.', ',').replace('_', '.')
"{:_.2f}".format(num).replace('.', ',').replace('_', '.')
这里有一个更简单的解决方案:
one = "1"
print(int(one))
>>> 1
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]
%i
或%d
可能更适用于%s
。如果number
是一个整数,print("The number is %i." % number)
也可以正常工作。 - undefined