首页 > 解决方案 > 替换文件夹名称的多个字符

问题描述

我在 Windows 上,Windows 不喜欢文件夹名称中的字符 '?/"|:*<>'。现在我不想用 '_' 替换所述字符。如果我使用它似乎可以工作.replace(':', '_')但不使用任何其他字符。但无论如何,我想替换所有上述字符。我试过(somestring).replace(':', '_').replace('?', '_')但它不起作用。

现在情况如何:

with open(unidecode(somestring).replace(':', '_')+'/{0}_{1}.txt'.format(counter, points), 'w+', encoding='utf-8') as outfile: outfile.write('{0}\n\n{1}\n'.format(stringhere, somecontent))

如前所述,它取代了':'就好了。但没有其他角色。在这种情况下如何替换多个字符?

标签: pythonreplace

解决方案


利用regex

import re
fe = '?/"|:*<>?/abcdefg"|:*<>'
ke = re.sub(r'[?/"|:*<>]', '_', fe)

>>> fe
'?/"|:*<>?/abcdefg"|:*<>'

>>> ke
'__________abcdefg______'

推荐阅读