Reputation: 63
Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!
import re
def demicrosoft (fn):
"""Clean up a file name.
Remove all parentheses and replace all spaces by underscores.
Params: fn (string):
Returns: (string) clean version of fn
"""
fn = re.sub('[()]', '', fn)
for ch in ['']:
fn = fn.translate(ch, "_")
return fn
print(demicrosoft('Quercus stellata (26).jpg'))
Upvotes: 0
Views: 1173
Reputation: 114108
newString = re.sub("([\s\(\)])",lambda m:"_" if b.group(0) not in "()" else "",targetString)
im guessing its for a performance reasons and they want O(N)
the generator expression should work ... here is an re
solution
Upvotes: 0
Reputation: 292
From Zen of Python: Readability counts!
def demicrosoft (fn):
dest = ""
for char in fn:
if char == ' ':
dest += '_'
elif char not in '()':
dest += char
return dest
Upvotes: 0
Reputation: 1884
import re
def demicrosoft (fn):
return '_'.join((''.join(re.split(r'[()]', fn)).split()))
Upvotes: 1
Reputation: 8610
You can use join
combined with a generator that iterates over the characters in your string while handling the logic for filtering out parentheses and replacing spaces with underscores:
PARENS = {'(', ')'}
def demicrosoft(string):
return ''.join('_' if c == ' ' else c for c in string if c not in PARENS)
print(demicrosoft('Quercus stellata (26).jpg')) # Quercus_stellata_26.jpg
Upvotes: 1