Akbar Hussein
Akbar Hussein

Reputation: 360

PYTHON - Change local variable in a function as needed; but leaving the default value

I have a function that takes a string (x) and and return a string that doesn't contain certain punctuation (not all punctuation are removed). I want the function to be customized for every situation. For example, sometimes I want to leave the exclamation mark !!! and not remove it. Here is my code:

def remove_extra(x):
    '''Remove punctuation from a string as needed'''
    leave = ['‘', '—', '-', ' ', '’', '\n']
    new_x = []
    for i in x:
        if i.isalpha() or i in leave:
            new_x.append(i)
    new_x = ''.join(new_x)
    return new_x

I could easily create a new function and change the local variable leave; but that's extra work... I am thinking about decorators; but as beginner it seems to me it'll complicate the solution not simplify it.

Please give me your suggestions. I want the original function remove_extra() customizable.

Upvotes: 0

Views: 79

Answers (2)

Akbar Hussein
Akbar Hussein

Reputation: 360

Thanks to @wim and @progmatico; putting optional argument solves the problem. I think it can be improved with decorators (containing properties)...

def remove_extra(x, *args):
    '''Remove punctuations from string as needed'''
    leave = ['‘', '—', '-', ' ', '’', '\n']
    leave.extend(args)
    new_x = []
    for i in x:
        if i.isalpha() or i in leave:
            new_x.append(i)
    new_x = ''.join(new_x)
    return new_x

Upvotes: 1

Henry Harutyunyan
Henry Harutyunyan

Reputation: 2415

This will do the trick.

def remove_extra(x, extra=None):
    '''Remove punctuation from a string as needed'''
    leave = ['‘', '—', '-', ' ', '’', '\n']
    if isinstance(extra, list):
        leave.extend(extra)
    new_x = []
    for i in x:
        if i.isalpha() or i in leave:
            new_x.append(i)
    new_x = ''.join(new_x)
    return new_x

foo = 'This is test sentence with!!!'

print(remove_extra(foo))
print(remove_extra(foo, ['!', ',']))

Output:

This is test sentence with
This is test sentence with!!!


If you want to use *args here is the possible solution

def remove_extra(x, *args):
    '''Remove punctuations from string as needed'''
    leave = ['‘', '—', '-', ' ', '’', '\n']
    leave.extend(args)
    new_x = []
    for i in x:
        if i.isalpha() or i in leave:
            new_x.append(i)
    new_x = ''.join(new_x)
    return new_x

foo = 'This is test sentence with!!!'

print(remove_extra(foo))
print(remove_extra(foo, '!', ','))

Output:

This is test sentence with
This is test sentence with!!!

Upvotes: 4

Related Questions