如何在Python中将int转换为字符串?!
当用户希望根据需要将一种数据类型转换为另一种数据类型时,有时需要进行类型转换。
Python具有str()将整数转换为字符串的内置函数。除此以外,我们还将讨论在Python中将int转换为字符串的各种其他方法。
使用str()
这是最常用的将int转换为字符串的方法,Python.Thestr()以整数变量为参数,将其转换为字符串。
语法
str(integer variable)
例子
num=2
print("Datatype before conversion",type(num))
num=str(num)
print(num)
print("Datatype after conversion",type(num))输出
Datatype before conversion2 Datatype after conversion
该type()函数给出作为参数传递的变量的数据类型。
上面代码中,转换前num的数据类型为int,转换后num的数据类型为str(即python中的string)。
使用f字符串
语法
f ’{integer variable}’例子
num=2
print("Datatype before conversion",type(num))
num=f'{num}'
print(num)
print("Datatype after conversion",type(num))输出
Datatype before conversion2 Datatype after conversion
使用“%s”关键字
语法
“%s” % integer variable
例子
num=2
print("Datatype before conversion",type(num))
num="%s" %num
print(num)
print("Datatype after conversion",type(num))输出
Datatype before conversion2 Datatype after conversion
使用。format()功能
语法
‘{}’.format(integer variable)例子
num=2
print("Datatype before conversion",type(num))
num='{}'.format(num)
print(num)
print("Datatype after conversion",type(num))输出
Datatype before conversion2 Datatype after conversion
这些是在Python中将int转换为string的一些方法。在某些情况下,我们可能需要将int转换为string,例如将保留在int中的值附加到某个字符串变量中。一种常见的情况是反转整数。我们可以将其转换为字符串然后反转,这比实现数学逻辑来反转整数更容易。
热门推荐
10 简短56岁生日祝福语
11 买房的祝福语高级简短
12 新年酒席开席祝福语简短
13 送灯祝福语简短独特
14 出阁祝福语简短句子
15 简短的祝福语12字
16 生病祝福语简短文案
17 收生日红包祝福语 简短
18 虎年新年专属祝福语简短