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