2016-09-30 2 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'는 공백입니까? ''''을''_ ''로 대체하려고 할 때''_ ''을 의미하지 마십시오.''''''로''''를 대체하려고합니다. – AChampion

+1

왜 그냥'return re.sub ('[()]', '', fn) .replace ('', '_')' – thefourtheye

+0

왜 파일 이름에 공백, 괄호 및 대괄호가 없습니까? 그것들은 모두 최신 파일 시스템의 유효한 파일 이름 문자입니다. – Anthon

답변

2

당신은이에 대한 replace s의 수를 체인 단지 수 있습니다

import re 
def demicrosoft (fn): 

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

는 "_"+ 채널에서 대체 에서 전화를 채널을 제거 this with str.translate() :

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

당신이 할 수있는 다음과 같이

a = 'a bad file name (really)' 

>>> a.replace('(', '').replace(')', '').replace(' ', '_') 
'a_bad_file_name_really' 
관련 문제