python 多个字符替换为一个字符(简洁代码)

在windows系统当中的文件命名,有些特殊字符是不能存在,下面我们来看一下哪些字符不能存在。

文件名称中不能包含\ / : * ? " < > |一共9个特殊字符


一开始想用replace()替换,但是要处理多个字符,写起来代码不整洁

每次只能替换一个字符或字符串!!!

msg = "Hello/world\Hello|Python|?*"
msg = msg.replace('\\', ' ').replace('/',' ').replace('|',' ').replace(':',' ').replace('*',' ').replace('?',' ').replace('"',' ').replace('>',' ').replace('<',' ')
print(msg)

输出内容

解决办法

re.compile(r"[abc]"),其中abc就是你想要去掉并更换为-的内容

import re
str2 = "/\|mrflysand *?,/ <>mrflysand 456!"
pat2 = re.compile(r"[*?:\"<>/|\\]")
result2 = pat2.sub("-",str2)
print(result2)

输出内容:

---mrflysand --,- --mrflysand 456!
posted @ 2023-08-14 17:41  MrFlySand-飞沙  阅读(130)  评论(0编辑  收藏  举报