python基础语法学习-字符串

1.什么是字符串

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
什么是字符串?
python3里面是unicode序列
在python2里面是byte序列
字符串也是不可变的
支持切片 也支持索引 支持解包操作
支持遍历
用在哪些特定的环境
为什么是内置数据结构
In [26]: s = 'geek'
In [27]: s
Out[27]: 'geek'
In [28]: s[0]
Out[28]: 'g'
可以反转:
In [30]: s[::-1]
Out[30]: 'keeg'
In [31]:
支持解包
In [36]: a = 'geek'
In [37]: g,*s = a
In [38]: g
Out[38]: 'g'
In [39]: s
Out[39]: ['e', 'e', 'k']
In [40]:

2.字符串的连接

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
**join使用方法:**
In [45]: list = ['my','name','is ','steven']
In [46]: list
Out[46]: ['my', 'name', 'is ', 'steven']
In [47]: ' '.join(list)
Out[47]: 'my name is steven'
In [48]: ','.join(list)
Out[48]: 'my,name,is ,steven'
In [49]:
###字符串的分割
**split** 从左边开始分割
**rsplit** 从右边开始分割
**splitlines**
**partition**
**rpartotion**
**split练习使用**
In [119]: a = "my name is steven"
In [120]: a
Out[120]: 'my name is steven'
In [121]: a.split()
Out[121]: ['my', 'name', 'is', 'steven']
In [122]: a.split('is')
Out[122]: ['my name ', ' steven']
In [123]: a.split(' ', 1)
Out[123]: ['my', 'name is steven']
In [124]: a.split(' ', 2)
Out[124]: ['my', 'name', 'is steven']
In [125]: a.split(' ', 3)
Out[125]: ['my', 'name', 'is', 'steven']
In [126]: a.split(' ', 4)
Out[126]: ['my', 'name', 'is', 'steven']
In [127]: a.split(' ', -1)
Out[127]: ['my', 'name', 'is', 'steven']
案例:
In [131]: line = 'usr:http://opsnotes.net'
In [132]: line.split()
Out[132]: ['usr:http://opsnotes.net']
In [133]: line.split(':', 1)
Out[133]: ['usr', 'http://opsnotes.net']
In [135]: key, value = line.split(':', 1)
In [136]: key
Out[136]: 'usr'
In [137]: value
Out[137]: 'http://opsnotes.net'
In [138]:
**splitlines的使用方法:**
In [138]: text = '''i an geek
.....: i an a boy'''
In [139]: text
Out[139]: 'i an geek\ni an a boy'
In [140]: text.splitlines()
Out[140]: ['i an geek', 'i an a boy']
In [141]:
**partition的使用方法:**
In [141]: a
Out[141]: 'my name is steven'
In [142]: a.partition(' ')
Out[142]: ('my', ' ', 'name is steven')
In [143]: a.split(' ', 1)
Out[143]: ['my', 'name is steven']
In [144]: line.partition(':')
Out[144]: ('usr', ':', 'http://opsnotes.net')
In [145]: key, _, value = line.partition(':')
In [146]: key
Out[146]: 'usr'
In [147]: _
Out[147]: 'usr'
In [148]: value
Out[148]: 'http://opsnotes.net'
In [149]:

3.字符串修改

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
84
85
86
87
88
89
自然语言修改
会返回一个新的字符串不会修改原来的需求
In [23]: a
Out[23]: 'my name is steven'
In [24]: a.capitalize()
Out[24]: 'My name is steven'
In [25]: a.title()
Out[25]: 'My Name Is Steven'
In [26]: a.lower()
Out[26]: 'my name is steven'
In [27]: a.upper()
Out[27]: 'MY NAME IS STEVEN'
大小写转换通常用在我们做比较的时候。
####程序世界的修改(center ljust rjust zfill)非重要
center是从两边开始填充
In [6]: a.center(80)
Out[6]: ' my name is steven '
In [7]: a.center(80,'#')
Out[7]: '###############################my name is steven################################'
In [8]:
In [8]: help(a.ljust)
Help on built-in function ljust:
ljust(...) method of builtins.str instance
S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
(END)
ljust的使用从右边开始填充
In [10]: a.ljust(80,'*')
Out[10]: 'my name is steven***************************************************************'
In [11]:
添加页码的方法:
In [12]: a.ljust(80) + '01'
Out[12]: 'my name is steven 01'
rjust是从左边开始填充
In [13]: a.rjust(80,'*')
Out[13]: '***************************************************************my name is steven'
In [14]:
zfill使用
In [14]: a.zfill(80)
Out[14]: '000000000000000000000000000000000000000000000000000000000000000my name is steven'
**strip** 全部的空白
**lstrip** 去除左边的空白
**rstrip** 去除右边的空白
**strip的使用方法**
In [15]: b = ' hah \n \t'
In [41]: b.strip()
Out[41]: 'hah'
In [42]: b.rstrip()
Out[42]: ' hah'
In [43]: b.lstrip()
Out[43]: 'hah \n \t'
In [44]:
In [17]:
In [26]: f = open('hello.py')
In [28]: f.readline
Out[28]: <function TextIOWrapper.readline>
In [29]: f.readline()
Out[29]: '#!/usr/bin/env python\n'
In [30]: f.readline().strip()
Out[30]: "print ('hello world!')"
In [31]: f.close()

4.字符串的判断

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
**startswith** 用的非常多
# **endswith** 用的非常多
**is_* 用的比较少
**startswith使用方法
In [47]: b = '##test##'
In [49]: b.startswith('#')
Out[49]: True
In [50]: b.startswith('##')
Out[50]: True
In [51]: b.startswith('###')
Out[51]: False
In [52]:
In [52]: line1 = "UUID=6634633e-001d-43ba-8fab-202f1df93339 / ext4 defaults,barrier=0 1 1"
In [53]: uuid = '6634633e-001d-43ba-8fab-202f1df93339'
In [54]: line1.startswith(uuid,5)
Out[54]: True
**endswith的使用方法,从后面判断
In [57]: line1
Out[57]: 'UUID=6634633e-001d-43ba-8fab-202f1df93339 / ext4 defaults,barrier=0 1 1'
In [58]: line1.endswith('0')
Out[58]: False
In [59]: line1.endswith('1')
Out[59]: True
In [60]:
**is_*的使用方法,多中判断
In [61]: line1.isupper()
Out[61]: False
In [62]: line1.islower()
Out[62]: False
In [63]: line1.isdigit()
Out[63]: False
In [64]: '123'.isdigit()
Out[64]: True
In [65]:

5.查找替换

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
**count**
**find**
**rfind**
**index**
**rindex**
**replace**
**count的用法,count统计可以统计一个字母也可以统计一个单词
In [13]: a
Out[13]: 'my name is steven'
In [14]: a.count('+')
Out[14]: 0
In [15]: a.count('m')
Out[15]: 2
In [16]: a.count('s')
Out[16]: 2
In [17]:
In [18]: a.find('s')
Out[18]: 9
**find的用法,最早出现的位置,可以找一个字符也可以找一个数字,查找索引,从开始查找
In [19]: a
Out[19]: 'my name is steven'
In [20]: a.find('s')
Out[20]: 9
In [21]: a.find('m')
Out[21]: 0
In [22]:
**index的使用方法
n [23]: a.index('t')
Out[23]: 12
In [24]: a.rindex('t')
Out[24]: 12
####index和find的区别,当一个不存在的时候
In [27]: a.rindex('c')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-27-b8abc29ea215> in <module>()
----> 1 a.rindex('c')
ValueError: substring not found
In [28]: a.find('c')
Out[28]: -1
In [29]:
**replace的使用方法
In [30]: s = 'abc123abc123'
In [31]: s.replace('abc','xyz')
Out[31]: 'xyz123xyz123'
In [32]: s
Out[32]: 'abc123abc123'
In [33]: s.replace('abc','xyz',1)
Out[33]: 'xyz123abc123'
In [35]: s.replace('abc','')
Out[35]: '123123'
In [36]: s.replace('abc','xyz', -1) 如果是负数不存在的时候 会全部被替换掉
Out[36]: 'xyz123xyz123'
In [37]:

6.字符串格式化

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
字符串格式化
In [4]: 'i an %s' % ('geek',)
Out[4]: 'i an geek'
In [5]:
template % tuple template % dict
In [5]: 'i an %(name)s' % {'name':'steven'}
Out[5]: 'i an steven'
In [9]: 'i am %s ' % 'steven'
Out[9]: 'i am steven '
In [10]:
小括号在代码里面有特殊意义,如果不加,会变成其他的
In [8]: 'i an %(name)s,my name is %(name)s' % {'name':'steven'}
Out[8]: 'i an steven,my name is steven'
In [9]:
什么时候需要字典?
内容反复出现
需要格式化更多内容很多
python中%i和%d没有区别 在C中有区别
In [11]: '%d' % 18
Out[11]: '18'
In [12]: '%i' % 18
Out[12]: '18'
In [13]: '%li' % 18 ####l会自动忽略掉
Out[13]: '18'
X代表16进制
In [14]: '%x' % 18
Out[14]: '12'
In [15]: '%X' % 18
Out[15]: '12'
In [16]: '%X' % 12
Out[16]: 'C'
In [17]: '%x' % 12
Out[17]: 'c'
In [18]:
e代表浮点数
In [19]: '%e' % 0.000015
Out[19]: '1.500000e-05'
In [20]: '%E' % 0.000015
Out[20]: '1.500000E-05'
In [21]:
字符串r和s的区别
任意都可以使用%s
%a 把中文修改成字符
%f 默认显示6位
In [3]: '%f is love' % 123
Out[3]: '123.000000 is love'
In [4]:
In [4]: '%+d' % 123
Out[4]: '+123'
In [5]: '%-d' % 123
Out[5]: '123'
In [6]: '%dd' % 123
Out[6]: '123d'
In [7]:
%s %d %f 是用的最多的
###format格式方法 python3的特性
In [7]: 'i am {}'.format('steven')
Out[7]: 'i am steven'
In [8]: 'i am {}, my age is {}'.format('steven',25)
Out[8]: 'i am steven, my age is 25'
In [9]: 'i am {1}, my age is {0}'.format('steven',25)
Out[9]: 'i am 25, my age is steven'
In [11]: 'i am {name}, my age is {age}'.format(name='steven',age=25)
Out[11]: 'i am steven, my age is 25'
In [12]:
In [13]: 'i am {0}, my name is {0}'.format('steven',25)
Out[13]: 'i am steven, my name is steven'
In [14]:format(里面参数是从0开始)
关键字要在后,两边对应,format后面要从0开始计数
In [15]: '{} {} {name}'.format(1,2,name='steven')
Out[15]: '1 2 steven'
In [16]: '{} {name} {}'.format(1,2,name='steven')
Out[16]: '1 steven 2'
In [17]: '{name} {} {}'.format(1,2,name='steven')
Out[17]: 'steven 1 2'
In [18]:
In [19]: 'i {}, name {}, age {}, sex {}'.format('steven', 28, 'steven', 'M')
Out[19]: 'i steven, name 28, age steven, sex M'
In [20]:
居中左边右边对齐
In [21]: '{0:80}'.format('学习成长')
Out[21]: '学习成长 '
In [22]: '{0:^80}'.format('学习成长')
Out[22]: ' 学习成长 '
In [23]: '{0:<80}'.format('学习成长')
Out[23]: '学习成长 '
In [24]: '{0:80}'.format('学习成长')
Out[24]: '学习成长 '
In [25]: '{0:>80}'.format('学习成长')
Out[25]:
+号如果是负数 不管加不加都显示负数,其中0是索引
In [27]: '{0:+}'.format(10)
Out[27]: '+10'
In [28]: '{0:+}'.format(-10)
Out[28]: '-10'
In [29]: '{0:-}'.format(-10)
Out[29]: '-10'
In [30]: '{0:-}'.format(10)
Out[30]: '10'
In [31]:
//添加宽度之后类似于右对齐
In [31]: '{0:80}'.format(10)
Out[31]: ' 10'
//如果是字符串会报异常
In [36]: '{0:d}'.format(10)
Out[36]: '10'
In [37]: '{0:d}'.format(steven)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-37-48cb87f81982> in <module>()
----> 1 '{0:d}'.format(steven)
NameError: name 'steven' is not defined
In [38]:
OpsNotes wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!