1、删除指定位置的值:pop()函数
#删除字符串中的最后一个字符
s='helloworld2'
s_list=list(s)#将字符串转换为列表
s_list.pop(-1)#pop掉列表最后一个值,返回被pop掉的值
输出:
‘2’
''.join(s_list)#将pop之后的列表通过join()函数转换为字符串
输出:
‘helloworld’
2、删除指定值
法一:replace()函数
#删除掉第一次出现的w
s='hello,wworld'
s.replace('w','',1)#第一个参数为需要替换掉的值;第二个参数为替换值,这里因为要删除该值,直接用‘’替换;第三个count参数为替换次数,该参数为可选参数,如不设定,默认替换掉所有
输出:
‘hello,world’
#删除掉所有的w
s='hello,wworld'
s.replace('w','')#这里没有指定count参数,默认替换所有
输出:
‘hello,orld’
法二:正则表达式re.sub()函数
sub(pattern,repl, string, count=0, flags=0)
pattern:必选参数,需要替换掉的值,可以是特定值也可以是正则表达式
repl:必选参数,替换值
string:必选参数,需要执行替换操作的字符串
count:可选参数,替换次数,默认为值为0,替换掉所有符合条件的值
flags:可选参数,编译标志。(这个参数没有去深入了解,目前默认值是够用的)
import re
s='Hello,world!2222222222222Python is so44444444444 interesting!'
re.sub('[0-9]','',s)#count参数为默认值,用空字符替换掉所有数字
输出:
‘Hello,world!Python is so interesting!’
import re
s='Hello,world!222Python is so44444444444 interesting!'
re.sub('[0-9]','',s,1)#count参数值设置为1,替换一次
输出:
‘Hello,world!22Python is so44444444444 interesting!’
import re
s='Hello,world!222Python is so44444444444 interesting!'
re.sub('[0-9]+','',s,1)#正则表达式中'+'意味一次或多次
输出:
‘Hello,world!Python is so44444444444 interesting!’
import re
s='helllo,world'
re.sub('l','',s,1)#pattern参数使用明确的指定值
输出:
‘hello,world’