📌  相关文章
📜  在Python中将字符串转换为数字和将数字转换为字符串

📅  最后修改于: 2022-05-13 01:54:20.841000             🧑  作者: Mango

在Python中将字符串转换为数字和将数字转换为字符串

在Python中,可以使用各种内置函数将字符串或数字转换为多个字符串,例如 str()、int()、float() 等。让我们看看如何使用它们中的每一个。

示例 1:将Python字符串转换为 int:

Python3
# code
# gfg contains string 10
gfg = "10"
 
# using the int(), string is auto converted to int
print(int(gfg)+20)


Python3
# code
gfg = "10"
 
# float(gfg) gives 10.0
print(float(gfg)+2.0)


Python3
# code
gfg = 100
 
# str(gfg) gives '100'
print(str(gfg)+" is a 3 digit number")
 
# concatenation is performed between them
print(str(gfg)+"200")


Python3
# code
gfg = 20.0
 
# str(gfg) becomes '20.0'
print(str(gfg)+"is now a string")
 
# no addition is performed. concatenated output
print(str(gfg)+"30.0")


输出:

30

示例 2:将Python字符串转换为浮点数:

蟒蛇3

# code
gfg = "10"
 
# float(gfg) gives 10.0
print(float(gfg)+2.0)

输出:

12.0

示例 3:将Python int 转换为 String:

这是通过使用 str()函数实现的,如下所示

蟒蛇3

# code
gfg = 100
 
# str(gfg) gives '100'
print(str(gfg)+" is a 3 digit number")
 
# concatenation is performed between them
print(str(gfg)+"200")

输出:

100 is a 3 digit number
100200

示例 4:将Python浮点数转换为字符串

这是通过使用 str()函数实现的,如下所示

蟒蛇3

# code
gfg = 20.0
 
# str(gfg) becomes '20.0'
print(str(gfg)+"is now a string")
 
# no addition is performed. concatenated output
print(str(gfg)+"30.0")

输出:

20.0is now a string
20.030.0