2016-09-30 95 views
2

这里是我做过什么:删除所有括号并用下划线替换所有空格?

import re 
def demicrosoft (fn): 

    fn = re.sub('[()]', '', fn) 
    for ch in [' ']: 
     fn = fn.replace(ch,"_"+ch) 
    return fn 
print(demicrosoft('a bad file name (really)')) 


>>> (executing lines 1 to 12 of "<tmp 2>") 
a_ bad_ file_ name_ really 

有位跟着一起下划线。我该如何解决它?

+1

你为什么要把空格加回''_'+ ch' - 'ch'是一个空格?你是不是只是指''_'' - 因为你试图用''_'替代'''','ch'是''''。 – AChampion

+1

为什么不只是'return re.sub('[()]','',fn).replace('','_')' – thefourtheye

+0

为什么文件名中的空格,括号和方括号不好?它们都是现代文件系统上的有效文件名字符。 – Anthon

回答

2

你可以只连锁一批replace S表示这样的:

a = 'a bad file name (really)' 

>>> a.replace('(', '').replace(')', '').replace(' ', '_') 
'a_bad_file_name_really' 
1

删除CH “_” + CH在更换电话如下

import re 
def demicrosoft (fn): 

    fn = re.sub('[()]', '', fn) 
    for ch in [' ']: 
     fn = fn.replace(ch,"_") 
    return fn 
2

你可以做这与str.translate()

>>> table = str.maketrans({'(':None, ')':None, ' ':'_'}) 
>>> 'a bad file name (really)'.translate(table) 
'a_bad_file_name_really' 
相关问题