我正在尝试创建一个函数,它将从字符串中删除任何文本块。例如,将“(example)somestuff”转换为“somestuff”,从字符串中删除任何被阻止的文本。这是一个大型程序的单个函数,用于根据文件名自动创建目录并将相关文件移动到所述文件夹中。我想我正陷入无休止的循环中,但却因为问题而陷入困境。
startbrackets = '[', '('
endbrackets = ']', ')'
digits = range(0,10)
def striptoname(string):
startNum = 0
endNum = 0
finished = True
indexBeginList = []
indexEndList = []
while (finished):
try:
for bracket in startbrackets:
indexBeginList.append(string.find(bracket, 0, len(string)))
except:
print "Search Start Bracket Failed"
wait()
exit()
# Testing Code START
finished = False
for i in indexBeginList:
if i != -1:
finished = True
startNum = i
break
# Testing Code END
try:
for bracket in endbrackets:
indexEndList.append(string.find(bracket, 0, len(string)))
except:
print "Search End Bracket Failed"
wait()
exit()
# Testing Code START
for i in indexEndList:
if i != -1:
endNum = i
break
# Testing Code END
if(finished):
if(startNum == 0):
string = string[:(endNum+1)]
else:
string = string[0:startNum]
for i in digits:
string.replace(str(i),"")
return string
答案 0 :(得分:0)
以下是使用re
的方法:
import re
def remove_unwanted(s):
# This will look for a group of any characters inside () or [] and substitute an empty string, "", instead of that entire group.
# The final strip is to eliminate any other empty spaces that can be leftover outside of the parenthesis.
return re.sub("((\(|\[).*(\)|\]))", "", s).strip()
print(remove_unwanted("[some text] abcdef"))
>>> "abcdef"
print(remove_unwanted("(example) somestuff"))
>>> "somestuff"