python第十四章:数据类型的转换

一,str函数

str()函数是Python的内置函数,用于将其他类型的数据转换为字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
num = 123
print(num)
print(type(num))
numStr = str(num)
print(numStr)
print(type(numStr))
 
flag = True
print(flag)
print(type(flag))
flagStr = str(flag)
print(flagStr)
print(type(flagStr))

运行结果:

123
<class 'int'>
123
<class 'str'>
True
<class 'bool'>
True
<class 'str'>

二,int函数

int()函数是Python的内置函数,用于将其他类型的数据转换为整数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
numStr = '456'
print(numStr)
print(type(numStr))
num = int(numStr)
print(num)
print(type(num))
 
flag = True
print(flag)
print(type(flag))
flagInt = int(flag)
print(flagInt)
print(type(flagInt))
 
numFloat = 3.1415
print(numFloat)
print(type(numFloat))
numInt = int(numFloat)
print(numInt)
print(type(numInt))

运行结果:

456
<class 'str'>
456
<class 'int'>
True
<class 'bool'>
1
<class 'int'>
3.1415
<class 'float'>
3
<class 'int'>

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/14/python-di-shi-si-zhang-shu-ju-lei-xing-de-zhuan-huan/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

三,float函数

float()函数是Python的内置函数,用于将其他类型的数据转换为浮点数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
numInt = 10
print("numInt值:", numInt, ",类型:", type(numInt))
numFloat = float(numInt)
print("numFloat值:", numFloat, ",类型:", type(numFloat))
 
numStr = "3.1415"
print("numStr值:", numStr, ",类型:", type(numStr))
numFloat = float(numStr)
print("numFloat值:", numFloat, ",类型:", type(numFloat))
 
numBool = True
print("numBool值:", numBool, ",类型:", type(numBool))
numFloat = float(numBool)
print("numFloat值:", numFloat, ",类型:", type(numFloat))

运行结果:

numInt值: 10 ,类型: <class 'int'>
numFloat值: 10.0 ,类型: <class 'float'>
numStr值: 3.1415 ,类型: <class 'str'>
numFloat值: 3.1415 ,类型: <class 'float'>
numBool值: True ,类型: <class 'bool'>
numFloat值: 1.0 ,类型: <class 'float'>
posted @ 2023-11-17 08:19  刘宏缔的架构森林  阅读(7)  评论(0编辑  收藏  举报