字符串
ord() 函数获取字符的 ASCII 码值
| 12
 3
 4
 5
 
 | print(ord('a'))print(ord('A'))
 
 output: 97
 output: 65
 
 | 
chr() 函数把 ASCII 转换为对应的字符
| 12
 3
 4
 5
 
 | print(chr(66))print(chr(97))
 
 output: B
 output: a
 
 | 
由于 Python 的字符串类型是 str,在内存中以 Unicode 表示,一个字符对应若干个字节。如果要在网络上传输,或者保存到磁盘上,就需要把 str 变为以字节为单位的 bytes。Python 对 bytes 类型的数据用带b前缀的单引号或双引号表示:
| 12
 3
 4
 5
 
 | print(type(b"a"))print(type("a"))
 
 output: <class 'bytes'>
 output: <class 'str'>
 
 | 
简写的方式是用 ASCII 编码为 bytes 所以不能用于中文,如果是中文需要 UTF-8 编码
| 12
 3
 4
 5
 6
 7
 
 | print(type(b"中文"))
 output:
 File "基础.py", line 19
 print(type(b"中文"))
 ^
 SyntaxError: bytes can only contain ASCII literal characters.
 
 | 
以 Unicode 表示的 str 通过 encode() 方法可以编码为指定的 bytes
| 12
 3
 
 | print(type("中文".encode("utf-8")))
 output: <class 'bytes'>
 
 | 
要计算 str 包含多少个字符,可以用 len() 函数
| 12
 3
 
 | print(len("abc中文"))
 output: 5
 
 | 
len() 函数计算的是 str 的字符数,如果换成 bytes,len() 函数就计算字节数
| 12
 3
 
 | print(len("abc中文".encode("utf-8")))
 output: 9
 
 | 
% 运算符就是用来格式化字符串的
| 12
 3
 
 | print("hello %s, I'm %s, %d years old." % ("world", "Tom", 20))
 output: hello world, I'm Tom, 20 years old.
 
 | 
list 类型
获取最后一个和倒数第二个元素
添加元素
删除最后一个元素
删除指定元素
初始化字符数组
元组
| 12
 3
 4
 5
 6
 7
 
 | t = (1, 2)print(t[0])
 print(t[1])
 
 output:
 1
 2
 
 | 
只有 1 个元素的 tuple 定义时必须加一个逗号 , ,来消除歧义。
因为,括号 () 既可以表示 tuple,又可以表示数学公式中的小括号,这就产生了歧义。
| 12
 3
 4
 
 | t1 = (1,)print(t1[0])
 
 output: 1
 
 | 
条件判断
| 12
 3
 4
 5
 6
 7
 
 | age = 13if age >= 18:
 print("adult")
 elif age > 6:
 print("teenager")
 else:
 print("kid")
 
 | 
input() 返回的数据类型是 str,所以这里需要转换为 int 类型。
| 12
 3
 4
 5
 
 | birth = int(input("birth: "))if birth < 2000:
 print('00前')
 else:
 print('00后')
 
 | 
循环
| 12
 3
 4
 5
 
 | for num in list(range(0, 20, 2)):print(num)
 
 for num in (1, 2):
 print(num)
 
 | 
字典类型,dict
| 12
 3
 4
 5
 
 | d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print(d['Bob'])
 print("Bob" in d)
 d.pop("Bob")
 print(d)
 
 | 
set
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | s = set([1, 2, 3]) print(s)
 print(type(s))
 s1 = {1, 2, 3}
 print(type(s1))
 s1.add(4)
 print(s1)
 s1.remove(4)
 print(s1)
 
 s1.add(8)
 s1.add(9)
 print(s1 & s)
 print(s1 | s)
 
 |