Python 数据类型与进制转换全解析:从基础到实战
·
前言:为什么要学数据类型
很多刚学 Python 的同学写代码时总会报错:字符串和数字不能相加、想要得到整数输出却输出小数、小数计算结果不对…… 根源就是分不清数据类型。 数据类型决定变量能存什么、能做什么运算。笔者只讲最常用的基础类型,全部附带可运行代码,零基础也能看懂。
小知识
1.type () 查看数据类型
type(a) #a的数值类型
1 Python的基本数据类型
我们都知道C 语言标准的四大基础类型:整型、字符型、浮点型、布尔型(C99),外加空类型 void ,在python中则有 整数、浮点数、字符串、布尔值、空值,这五大基本的数据类型。下面我将介绍一下这五种数据类型:
1 整数int
存储整数 声明一个整数
num = 100
print(num, type(num))
E:\python2607\level1>python 4.数值类型.py
100 <class 'int'>
E:\python2607\level1>
2浮点数 float
声明一个浮点数
f1 = 3.14159
print(f1, type(f1))
f1 = -3.14159
print(f1, type(f1))
E:\python2607\level1>python 4.数值类型.py
3.14159 <class 'float'>
-3.14159 <class 'float'>
E:\python2607\level1>
3字符串 str
声明一个字符串
str1 = "hello world"
print(str1, type(str1))
str2 = 'hello world'
print(str2, type(str2))
str4 = "fgfgjrhfg'''gjghjh"
print(str4, type(str4))
str5 = 'fgfgjrhfg""""gjghjh'
print(str5, type(str5))
hello world <class 'str'>
hello world <class 'str'>
fgfgjrhfg'''gjghjh <class 'str'>
fgfgjrhfg""""gjghjh <class 'str'>
4布尔 bool
声明一个布尔值
b1 = True
print(b1, type(b1))
b2 = False
print(b2, type(b2))
True <class 'bool'>
False <class 'bool'>
5空值 None
声明一个变量 但是又不存储任何数据
num = None
print(num, type(num))
None <class 'NoneType'>
2 Python整数进制转换
我们常见的进制表示有 二进制、八进制、十进制、 十六进制,下面我将介绍这些进制:
十进制Decimal
基数:10,数字:0,1,2,3,4,5,6,7,8,9 日常人类使用。
二进制Binary
基数:2,数字:0、1 计算机底层存储只用二进制。 前缀标识:0b
十六进制Hexadecimal
基数:16,数字:0~9,A (10)、B (11)、C (12)、D (13)、E (14)、F (15) 常用于内存、颜色、地址。 前缀标识:0x
八进制Octal
基数:8,数字:0~7 前缀标识:0o
下面展示Python中的进制进制表示与转换代码
i = 9
print(i, type(i))
9 <class 'int'>
b = 0b01110
print(b, type(b))
14 <class 'int'>
c = 0x1f
print(c, type(c))
31 <class 'int'>
o = 0o765
print(o, type(o))
501 <class 'int'>
进制转换函数
#int函数 将某进制转换为10进制
#base表示字符串内容是几进制
print(int("6474758", base=10))
print(int("10011001", base=2))
print(int("faa5f", base=16))
print(int("77764", base=8))
6474758
153
1026655
32756
#bin函数 10->2
print(bin(1000))
#oct函数 10->8
print(oct(1000))
#hex函数 10->16
print(hex(1000))
0b1111101000
0o1750
0x3e8
3 Python数据类型转换函数
int
#int 可以将数字类型的字符串转整数
v = int("fa336fbce", base=16)
print(v, type(v))
#int 可以将小数转为整数
v2 = int(3.12222)
print(v2, type(v2))
#int 可以将bool值转为整数
v3 = int(True)
v4 = int(False)
print(v3, v4)
67162799054 <class 'int'>
3 <class 'int'>
1 0
float
#float可以将数值类型(最多一个小数点)的字符串转为浮点数
f1 = float("19999345655474")
print(f1, type(f1))
f2 = float(10333)
print(f2, type(f2))
f3 = float("1.223355")
print(f3, type(f3))
f4 = float(True)
f5 = float(False)
print(f4, f5)
19999345655474.0 <class 'float'>
10333.0 <class 'float'>
1.223355 <class 'float'>
1.0 0.0
bool
#任意类型都可以转换为布尔类型
b1 = bool("yueiwrghuiryh32yh23")
print(b1)
b2 = bool(123)
print(b2)
b3 = bool(1.44566)
print(b3)
b4 = bool("")
print(b4)
b5 = bool()
print(b5)
True
True
True
False
False
str
#任意类型都可以转换为字符串
s1 = str(235434654)
print(s1)
s2 = str("‘’34546……%#¥&‘’‘’‘)((()Tgvgd")
print(s2)
s3 = str("True")
print(s3)
s4 = str(True)
print(s4)
235434654
‘’34546……%#¥&‘’‘’‘)((()Tgvgd
True
True
更多推荐


所有评论(0)