我在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))
如前所述,它可以很好地代替':'。但没有其他角色。在这种情况下如何替换多个字符?
答案 0 :(得分:1)
使用regex
import re
fe = '?/"|:*<>?/abcdefg"|:*<>'
ke = re.sub(r'[?/"|:*<>]', '_', fe)
>>> fe
'?/"|:*<>?/abcdefg"|:*<>'
>>> ke
'__________abcdefg______'
答案 1 :(得分:1)
这应该有效:
res = ''.join(['_' if letter in '?/"|:*<>' else letter for letter in fe])
print(res)
#__________abcdefg______