Search code examples
pythonstringloopsdictionarypunctuation

Remove punctation from every value in Python dictionary


I have a long dictionary which looks like this:

name = 'Barack.'
name_last = 'Obama!'
street_name = "President Streeet?"

list_of_slot_names = {'name':name, 'name_last':name_last, 'street_name':street_name}

I want to remove the punctation for every slot (name, name_last,...).

I could do it this way:

name = name.translate(str.maketrans('', '', string.punctuation))
name_last = name_last.translate(str.maketrans('', '', string.punctuation))
street_name = street_name.translate(str.maketrans('', '', string.punctuation))

Do you know a shorter (more compact) way to write this?

Result:

>>> print(name, name_last, street_name)
>>> Barack Obama President Streeet

Solution

  • name = 'Barack.'
    name_last = 'Obama!'
    empty_slot = None
    street_name = "President Streeet?"
    
    print([str_.strip('.?!') for str_ in (name, name_last, empty_slot, street_name) if str_ is not None])
    
    -> Barack Obama President Streeet
    

    Unless you also want to remove them from the middle. Then do this

    import re
    
    name = 'Barack.'
    name_last = 'Obama!'
    empty_slot = None
    street_name = "President Streeet?"
    
    print([re.sub('[.?!]+',"",str_) for str_ in (name, name_last, empty_slot, street_name) if str_ is not None])