Python replaces multiple characters with one character (concise code)

In file naming in Windows system, some special characters cannot exist. Let's take a look at which characters cannot exist.

\ / : * ? " < > |A total of 9 special characters cannot be included in the file name


At first I wanted to use replace() to replace, but I had to deal with multiple characters and the code was not neat to write.

Only one character or string can be replaced at a time! ! !

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

Output content

Solution

re.compile(r"[abc]"), which is what abcyou want to remove and replace with-

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

Output content:

---mrflysand --,- --mrflysand 456!

Guess you like

Origin blog.csdn.net/MrFlySand/article/details/132289162