2016-09-30 93 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' 
相關問題