strip()
- strip() 去掉字符串两边的空格
## 不传参时,默认去掉两边空格
>>>thestring = ' say you later '
>>>thestring.strip()
'say you later'
## 传入单个字符
>>>thestring = 'say the ays'
>>>thestring.strip('s') # 去掉两边的's'
'ay the ay'
## 传入字符数组
>>>thestring = 'saaay yes or no yaaaas'
>>>thestring.strip('say')
' yes or no '
>>>thestring
'saaay yes or no yaaaas'
## 传入字符数组时,编译器去除两端所有相应的字符,thestring 依次被去除首尾在['s','a','y']列表内的字符,
## 直到字符不在数组内,输出' yes or no ' ,输出的两端分别还有一个空格,因为编译器检测到是空格,不在
## 列表内,所以停止;.strip()生成副本,不改变原有字符串
- lstrip() 去除字符串左边的空格 rstrip() 去除字符串右边的空格
## 不传参
>>>thestring = ' say you later '
>>>thestring.lstrip() # 默认去掉左边空格
'say you later '
>>>thestring.rstrip() # 默认去掉右边空格
' say you later'
## 传入字符数组
>>>thestring = 'saaay yes or no yaaaas'
>>>thestring.lstrip('say') # 去掉左边的's''a''y'
' yes or no yaaaas'
>>>thestring.rstrip('say') # 去掉右边的's''a''y'
'saaay yes or no '
strip() 传入的参数,看似是连在一起的字符串,实则是拆分成单个的字符列表
split()
split()作用是对字符串进行分割,默认按空格分割
- 按某个字符分割,如按 ‘.’ 进行分割
>>>str = 'www.westos.com'
>>>str.split('.')
['www', 'westos', 'com'] # 返回一个列表
- 按某个字符分割,且分割 n 次, 如按 ‘.’ 进行分割1次
>>>str = 'www.westos.com'
>>>str.split('.',1)
['www', 'westos.com']
>>>str1,str2 = str.split('.',1) # 分割后的字符串赋值给 n+1 个变量
>>>print(str1,str2)
www westos.com
- 例题:提取下面字符串中的 50,0,51
>>>str = 'xxxxxxx5 [50,0,51]>, xxxxxxxxx'
>>>lst = str.split('[')[1].split(']')[0].split(',')
>>>print(lst)
['50','0','51']
# 分解如下
>>>list = str.split('[') # 按照左括号分割
>>>print(list)
['xxxxxxx5 ', '50,0,51]>, xxxxxxxxx']
>>>str.split('[')[1].split(']') # 再对list的索引为1的元素按']'进行分割
['50,0,51', '>, xxxxxxxxx']
>>>str.split('[')[1].split(']')[0] # 提取分隔后的第一个元素
'50,0,51'
>>>str.split('[')[1].split(']')[0].split(',') # 对提取后的按 ',' 分割
['50', '0', '51']
divmod()
返回的商和余数是一个 tuple
## 格式: divmod(被除数,除数)
## 返回值:(商,余数)
>>> t = divmod(7,3)
>>> t
(2, 1)
>>> quot,rem = divmod(7,3)
>>> print(quot,rem)
2 1
join()
使用join()函数,可以把一个 list 或者 tuple 中所有的元素按照定义的分隔符 (sep) 联系起来,仅限于元素是字符型
>>> a = ['a','b','c'] # 只能是字符型
>>> x = '|'.join(a)
>>> x
'a|b|c'
>>> s = [1,2,3] # 不能是其他类型
>>> x = '|'.join(s)
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
x = '|'.join(s)
TypeError: sequence item 0: expected str instance, int found
zip()
使元素一一对应
>>> s1='abc'
>>> s2='123'
>>> for i in zip(s1,s2):
print(i)
('a', '1')
('b', '2')
('c', '3')
>>> for i in zip(s1,s2):
print(' '.join(i)) # 用空格分隔并联系起来
a 1
b 2
c 3
enumerate()
enumerate() 函数用于遍历序列中的元素以及它们的下标
>>> for i,v in enumerate('hello'):
print(i,v)
0 h
1 e
2 l
3 l
4 o
>>> for i,v in enumerate(['a','b','c']):
print(i,v)
0 a
1 b
2 c
>>> for i,v in enumerate(('a','b','c')):
print(i,v)
0 a
1 b
2 c