Mengchen Ding
Mengchen Ding

Reputation: 63

How to replace all spaces by underscores and remove all the parentheses without using replace() function?

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

Answers (4)

Joran Beasley
Joran Beasley

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

bitfhacker
bitfhacker

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

Dan
Dan

Reputation: 1884

import re
def demicrosoft (fn):
  return '_'.join((''.join(re.split(r'[()]', fn)).split()))

Upvotes: 1

Karin
Karin

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

Related Questions