在爬虫有一些需求需要把多个空格替换一个或者是把多个相同的字符值保留一个,实现方法用re.sub
直接上代码
strs = "核算处 期"
new_strs = re.sub(r" +",' ', strs)
print(new_strs)
strs = "核算处-----------期"
new_strs = re.sub(r"-+",'-', strs)
print(new_strs)
输出结果是:
成功实现了多个空格替换为一个,多个-替换成一个。
在爬虫有一些需求需要把多个空格替换一个或者是把多个相同的字符值保留一个,实现方法用re.sub
直接上代码
strs = "核算处 期"
new_strs = re.sub(r" +",' ', strs)
print(new_strs)
strs = "核算处-----------期"
new_strs = re.sub(r"-+",'-', strs)
print(new_strs)
输出结果是:
成功实现了多个空格替换为一个,多个-替换成一个。