Home > Article > Backend Development > What are the basic data types of Python and how to use them
The default input is decimal
Binary 0b, Octal 0o, Hexadecimal 0x
16 == 0b10000 == 0o20 == 0x10rrree
Conversion between decimal and other bases
True
a = bin(16) # 转二进制 b = oct(16) # 转八进制 c = hex(16) # 转十六进制 print(a, b, c)
Note: The result after the above conversion is of string type, so if an equality comparison is performed, the output is False result
0b10000 0o20 0x10
a == b == c
False
type(a)
Convert other bases to decimal
str
d = int(a, 2) # 二进制转十进制 e = int(b, 8) # 八进制转十进制 f = int(c, 16) # 十六进制转十进制 print(d, e, f)
Uncertain decimal problem
16 16 16
(0.1+0.2) == 0.3
False
0.1+0.2
Computers use binary decimals to represent the decimal part of floating point numbers
Reason: Some decimals cannot be completely represented by binary decimals
0.30000000000000004
0.00011001100110011001 0.09999942779541016 0.0011001100110011 0.1999969482421875 0.01001100110011001 0.29999542236328125 0.01100110011001101 0.40000152587890625 0.1 === === 0.5
Normally it will not affect the calculation accuracy
二进制 十进制
0.1 + 0.7
Round to get the accuracy Solution
can be solved by rounding: round(parameter, retain the number of decimal places)
0.7999999999999999
a = 3*0.1 print(a)
0.30000000000000004
b = round(a, 1) print(b) b == 0.31.1.3 Complex numbers - a bj
0.3 True
3+4j 2+5J
(2+5j)1.2 Numeric operation operators (a operator b)
2+1j
(1+3-4*2)/5
-0.8
x = 1 -x
-1
2**3
8
13//5 # 整数商 x/y 向下取整数
2
A few notes
13 % 5 # 模运算 余数 13=2*5+3
1+1.5
2.5
2/5
0.4
8/41.3 Numerical operation function function(x, ...)
2.0
abs(-5)
5
abs(3+4j) # 对复数a+bj 执行的是求模运算(a^2+b^2)^0.5
5.0
pow(2, 5) # pow(x,n) x的n次方 等价于x**n
32
pow(2, 5, 3) # 2^5 % 3 更快速
2
a = 1.618 print(round(a)) # 默认四舍五入为整数
2
print(round(a, 2)) # 参数2表示四舍五入后保留2位小数
1.62
print(round(a, 5)) # 位数不足,无需补齐
1.618
divmod(13, 5) # 较(x//y,x % y)更快,只执行了一次x/y
(2, 3)
max(3, 2, 3, 6, 9, 4, 5)
9
a = [3, 2, 3, 6, 9, 4, 5] print("max:", max(a)) print("min:", min(a))
max: 9 min: 2
sum((1, 2, 3, 4, 5))
15
import math # 导入库 print(math.exp(1)) # 指数运算 e^x print(math.log2(2)) # 对数运算 print(math.sqrt(4)) # 开平方运算 等价于4^0.5
2.718281828459045 1.0 2.0
import numpy as np a = [1, 2, 3, 4, 5] print(np.mean(a)) # 求均值 print(np.median(a)) # 求中位数 print(np.std(a)) # 求标准差Part 2 String Type2.1 Expression of String
3.0 3.0 1.4142135623730951
print("Python") print('Python')
There is an odd in the double
Python Python
print("I'm 18 years old")
There is a double in the odd
print('"Python" is good')
"Python" is good
双中有双,单中有单——转义符 \
# print(""Python" is good") print("\"Python\" is good") # \ 字符
"Python" is good
转义符可以用来换行继续输入
s = "py\ thon" print(s)
python
s = "My name is Peppa Pig"
变量名[位置编号]
正向索引——从零开始递增
位置编号不能超过字符串的长度
空格也是一个位置
print(s[0]) print(s[2]) print(s[5])
M m
s = "My name is Peppa Pig"
反向索引——从-1开始递减
print(s[-1]) print(s[-3]) print(s[-5])
g P a
索引只能获得一个字符,如何获得多个字符?
变量名[开始位置:结束位置:切片间隔]
切片间隔如不设置默认为1,可省略
切片范围不包含结束位置(前闭后开)
s = "Python" print(s[0:3:1])
Pyt
print(s[0:3])
Pyt
print(s[0:3:2])
Pt
起始位置是0 可以省略
结束位置省略,代表可以取到最后一个字符
可以使用反向索引
s = "Python" print(s[0:6])
Python
print(s[:6])
Python
print(s[:])
Python
print(s[-6:])
Python
反向切片
起始位置是-1也可以省略
结束位置省略,代表可以取到第一个字符
关键点在于-1,代表前一个位置比后一个位置大-1
s = "123456789" print(s[-1:-10:-1])
987654321
print(s[:-10:-1])
987654321
print(s[::-1])
987654321
字符串1+字符串2
a = "I love " b = "my wife " a+b
'I love my wife '
字符串 * n n * 字符串
c = a+b print(c*3) print(3*c)
I love my wife I love my wife I love my wife I love my wife I love my wife I love my wife
子集in全集 任何一个连续的切片都是原字符串的子集
folk_singers = "Peter, Paul and Mary" "Peter" in folk_singers
True
"PPM" in folk_singers
False
遍历字符串字符 for 字符 in 字符串
for s in "Python": print(s)
P y t h o n
所含字符的个数
s = "python" len(s)
6
将中文字库,英文字母、数字、特殊字符等转化成计算机可识别的二进制数
每个单一字符对应一个唯一的互不重复的二进制编码
Python 中使用的是Unicode编码
将字符转化为Unicode码——ord(字符)
print(ord("1")) print(ord("a")) print(ord("*")) print(ord("中")) print(ord("国"))
49 97 42 20013 22269
将Unicode码转化为字符——chr(Unicode码)
print(chr(1010)) print(chr(10000)) print(chr(12345)) print(chr(23456))
ϲ ✐ 〹 宠
返回一个列表
原字符串不变
上述特性适合以下所有字符串处理方法
languages = "Python C C++ Java PHP R" languages_list = languages.split(" ")#括号里的参数就是我们希望对目标字符串进行分割的标记 print(languages_list) print(languages)
['Python', 'C', 'C++', 'Java', 'PHP', 'R'] Python C C++ Java PHP R
可迭代类型 如:字符串、列表
s = "12345" s_join = ",".join(s) #把可迭代的对象每一个都取出来,相邻两个之间加上聚合字符 s_join
'1,2,3,4,5'
序列类型的元素必须是字符类型
# s = [1, 2, 3, 4, 5] 无法使用聚合 s = ["1", "2", "3", "4", "5"] "*".join(s)
'1*2*3*4*5'
strip从两侧开始搜索,遇到指定字符执行删除,遇到非指定字符,搜索停止
类似的还有左删除lstrip和右删除rstrip
s = " I have many blanks " print(s.strip(" ")) #从两端进行搜索,遇到指定字符后删除空格,然后停止 print(s.lstrip(" ")) print(s.rstrip(" ")) print(s)
I have many blanks I have many blanks I have many blanks I have many blanks
s = "Python is coming" s1 = s.replace("Python","Py") print(s1)
Py is coming
s = "Python is an excellent language" print("an:", s.count("an")) print("e:", s.count("e"))
an: 2 e: 4
字符串.upper() 字母全部大写
s = "Python" s.upper()
'PYTHON'
字符串.lower() 字母全部小写
print(s.lower()) print(s)
python Python
字符串.title()首字母大写
s.title()
'Python'
a = 10 print(a > 8) print(a == 12) print(a < 5)
True False False
any() 数据有一个是非零就为True
all() 数据有一个是零就为False (元素都是非零的)
print(any([False,1,0,None])) # 0 False None 都是无 print(all([False,1,0,None]))
True False
n = 2800 while True: m = eval("请输入一个正整数:")) if m == n: print("正确") break elif m > n: print("太大了") else: print("太小了")
请输入一个正整数:280 太小了 请输入一个正整数:2800 正确
import numpy as np x = np.array([[1, 3, 2, 5, 7]]) # 定义 numpy数组 print(x > 3) x[x > 3]
[[False False False True True]] array([5, 7])
type(变量)
age = 20 name = "Ada" print(type(age)) print(type(name))
<class 'int'> <class 'str'>
isinstance(变量,预判类型) 承认继承
变量类型是预判类型的子类型,则为真,否则为假
print(isinstance(age, int)) # 承认继承 这里的int就相当于是一个类
True
print(isinstance(age, object)) print(isinstance(name, object)) # object 是所有类的老祖宗
True True
字符串检查方法
字符串.isdigit()字符是否只有数字组成
age = "20" name = "Ada"
age.isdigit()
True
name.isdigit()
False
字符串.isalpha()字符是否只有字母组成
name.isalpha()
True
age.isalpha()
False
字符串.isalnum()字符是否只有数字和字母组成
"Ada20".isalnum() # 比如可用于判断用户名是否合法
True
数字类型转字符串 str(数字类型)
age = 20 print("My age is "+str(age))
My age is 20
仅有数字组成的字符串转数字 int() float() eval(232, 232, 232); background: rgb(249, 249, 249);">
s1 = "20" s2 = "10.1"
int(s1) # 仅整型 # int(s2) 会错误
20
float(s1)
20.0
float(s2)
10.1
eval(232, 232, 232); background: rgb(249, 249, 249);">20
eval(232, 232, 232); background: rgb(249, 249, 249);">10.1
The above is the detailed content of What are the basic data types of Python and how to use them. For more information, please follow other related articles on the PHP Chinese website!