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

# 字符串长度和数量
s1 = "hello world"
print(len(s1)) # 11
print(s1.count('l')) # 3
# print(s1.count('l', 0, 4)) # 2, 范围[0,4)

# 大小写切换
s2 = "HELLO world"
print(s2.upper()) # 'HELLO WORLD'
print(s2.lower()) # 'hello world'

# title: 将每个单词的首字母大写. 标题化
print(s2.title()) # Hello World

# capitalize: 将整个字符串的首字母大写.
print(s2.capitalize()) # Hello world

# swapcase: 将大写变成小写, 将小写变成大写.
print(s2.swapcase()) # 'hello WORLD'


# eval(): 会将字符串的表达式内容进行运算.
s3 = '2+3'
print(eval(s3))
s4 = '[1,2,3]'
l4 = eval(s4)
print(l4, type(l4)) # [1, 2, 3] <class 'list'>

# a, b = eval(input("请输入2个数字(中间用逗号隔开):"))
# # a, b = eval("3,4") = 3,4
# print(a, b)

# 填充(了解)
print("hello".center(50))
print("hello".center(50, '-')) # 在50宽度居中显示,其他区域用'-'填充

print("hello".ljust(50, '-')) # 靠左 left
print("hello".rjust(50, '-')) # 靠右 right

print("hello".zfill(50)) # 靠右,其他地方用0填充


# 查找
# find() : 从左往右查找子字符串第一次出现的下标位置,如果不存在则返回-1
# rfind() : 从右往左查找子字符串第一次出现的下标位置,如果不存在则返回-1
s5 = "I like Python and Pycharm"
print(s5.find('Py')) # 7
print(s5.find('Py22')) # -1

print(s5.rfind('Py')) # 18
print(s5.rfind('Py22')) # -1

# index和rindex: 了解
# print(s5.rindex('Py')) # 7
# print(s5.rindex('Py22')) # 报错 ValueError: substring not found


# 提取
# strip()
print(" abc def ".strip()) # 'abc def', 默认将两边的空格去除
print("----韩 -- 信----".strip('-')) # '韩 -- 信'
print("----韩 -- 信----".lstrip('-')) # '韩 -- 信----'
print("----韩 -- 信----".rstrip('-')) # '----韩 -- 信'


# 判断: 掌握
print("HE".isupper()) # 是否为大写字母
print('h'.islower()) # 是否为小写字母

print('33'.isdigit()) # 是否为数字
print('a'.isalpha()) # 是否为字母
print('abcABC123'.isalnum()) # 是否为数字或字母

# print('Hello World'.istitle()) # 是否每个单词首字母大写,其他小写