1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

# 分割/拆分,分隔

s1 = "baoqiang is a green man"
print(s1.split()) # ['baoqiang', 'is', 'a', 'green', 'man']
print(s1.split(" ")) # ['baoqiang', '', 'is', 'a', 'green', 'man']
print(s1.split("a")) # ['b', 'oqi', 'ng is ', ' green m', 'n']
print(s1.split('baoqiang')) # ['', ' is a green man']
print(s1.split('marong')) # ['baoqiang is a green man'], 不存在则得到整个字符串组成的列表

# 使用前2个'a'进行分割: 了解
# print(s1.split("a", 2)) # ['b', 'oqi', 'ng is a green man']

s2 = '''床前明月光
疑是地上霜
举头望明月
低头思故乡'''

print(s2)

# splitlines: 按行分割
print(s2.splitlines()) # ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡']
print(s2.splitlines(True)) # ['床前明月光\n', '疑是地上霜\n', '举头望明月\n', '低头思故乡']

print(s2.split('\n')) # ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡']


# join() : 合并
l1 = ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡']
print("".join(l1)) # 床前明月光疑是地上霜举头望明月低头思故乡
print('\n'.join(l1))
print('++'.join(l1)) # 床前明月光++疑是地上霜++举头望明月++低头思故乡

# print('='.join(['a', 1, 2])) # 报错, 列表中需要是字符串的元素


# replace() : 替换
s3 = "贾乃亮 is a nice nice nice man"
s4 = s3.replace('nice', 'good') # '贾乃亮 is a good good good man'
s4 = s3.replace('nice', 'good', 2) # '贾乃亮 is a good good nice man', 只替换前2个
print(s4)
# 字符串是不可变的.

# 简单加密: 了解
t = str.maketrans("aco", "123")
print(t) # {97: 49, 99: 50, 111: 51}

print("today is a good day".translate(t))
# t3d1y is 1 g33d d1y

#
print("hello world".startswith("hello")) # True, 是否以指定字符串开头
print("hello world".endswith("ld")) # True, 是否以指定字符串结尾


# 编码:
# ASCII: 只适用于英文字母, 只用了一个字节, 0000 0000
# GBK,gb2312: 适用于中文
# Unicode
# utf-8 : 国际上比较通用的编码

# 编码解码: 掌握
# 编码: encode(): 字符串=>二进制
s5 = "python 你好"
r = s5.encode() # 默认是utf-8
r = s5.encode('utf-8')
# r = s5.encode('GBK')
print(r)
# b'python \xe4\xbd\xa0\xe5\xa5\xbd'

# 解码: decode(): 二进制 => 字符串
print(r.decode()) # 'python 你好'


# ord(): 字符=> ASCII码
# chr(): ASCII码=> 字符
print(ord('a')) # 97
print(chr(97)) # 'a'