python中列表元素的删除方法
1. 删除指定位置的值:pop()函数
- 可以结合
′
a
b
c
d
a
e
f
a
a
′
.
i
n
d
e
x
(
′
a
′
)
'abcdaefaa'.index('a')
′abcdaefaa′.index(′a′) 返回第一个字符a的索引;
s='hello, goodboy!'
s_=list(s)
s_.pop(-1)
''.join(s_)
2. 替换指定值
2.1 replace()函数
- replace()函数将会替换字符串中的所有需要替换的值;
s='hello,wworld'
s.replace('w','',1)
2.2 正则表达re.sub()函数
- sub(pattern,repl, string, count=0, flags=0)
- pattern:必选参数,需要替换掉的值,可以是特定值也可以是正则表达式;
- repl:必选参数,替换值;
- string:必选参数,需要执行替换操作的字符串;
- count:可选参数,替换次数,默认为值为0,替换掉所有符合条件的值;
- flags:可选参数,编译标志。(这个参数没有去深入了解,目前默认值是够用的)
import re
s='Hello,world!222Python is so44444444444 interesting!'
re.sub('[0-9]','',s,1)
import re
s='Hello,world!222Python is so44444444444 interesting!'
re.sub('[0-9]','',s,1)
import re
s='helllo,world'
re.sub('l','',s,1)
3. 删除指定值:remove()函数
- remove()函数每次删除给定字符在列表中中第一次出现的那个;
- remove()函数适用于list,不能直接用字符串调用;
>>> list('abcaaad').remove('a')
>>> a = list('abcaaad')
>>> a
['a', 'b', 'c', 'a', 'a', 'a', 'd']
>>> a.remove('a')
>>> a
['b', 'c', 'a', 'a', 'a', 'd']
>>> a.remove('a')
>>> a
['b', 'c', 'a', 'a', 'd']