python替换的几种操作:
主要replace(),re.sub(),以及split()切片替换
一:简单的某个字符替换:
replace()
函数
str.replace(old, new, num)
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换 num 次。
eg:
str = 'hello world!! <i love you>'
print(str.replace('!',',',1))
print(str.replace('!',','))
结果:
二:使用切片split()和join实现
这个在上篇 第六点里面也写过
str = 'hello world!! <i love you>'
new = '_hi'
new_str = str.split('!')
print(new.join(new_str))
三:正则替换
re.sub(pattern,repl,string,conut=0,flags=0)
参数:pattern正则表达式,repl要替换内容,string包含被替换内容的字符串,count查找替换的次数,返回一个string
如果没有找到匹配的,返回原字符串
import re
str = 'hello world!! <i love you>'
print(re.sub(r'[!<>]','_',str))
结果
例如Windows系统上创建的txt文档名字不能包含特殊的字符 \ / : * ? " < > |
我们可以
def setFileTitle(self,filename):
fileName = re.sub(r'[\/:*?"<>|]','-',filename)#去掉非法字符
self.file = open(fileName + ".txt","w+")