Search code examples
pythonpunctuation

How to remove the punctuation in the middle of a word or numbers?


For example if I have a string of numbers and a list of word:

My_number = ("5,6!7,8")
My_word =["hel?llo","intro"]

Solution

  • Using str.translate:

    >>> from string import punctuation
    >>> lis = ["hel?llo","intro"]
    >>> [ x.translate(None, punctuation) for x in lis]
    ['helllo', 'intro']
    >>> strs = "5,6!7,8"
    >>> strs.translate(None, punctuation)
    '5678'
    

    Using regex:

    >>> import re
    >>> [ re.sub(r'[{}]+'.format(punctuation),'',x ) for x in lis]
    ['helllo', 'intro']
    >>> re.sub(r'[{}]+'.format(punctuation),'', strs)
    '5678'
    

    Using a list comprehension and str.join:

    >>> ["".join([c for c in x if c not in punctuation])  for x in lis]
    ['helllo', 'intro']
    >>> "".join([c for c in strs if c not in punctuation])
    '5678'
    

    Function:

    >>> from collections import Iterable
    def my_strip(args):
        if isinstance(args, Iterable) and not isinstance(args, basestring):
            return [ x.translate(None, punctuation) for x in args]
        else:
            return args.translate(None, punctuation)
    ...     
    >>> my_strip("5,6!7,8")
    '5678'
    >>> my_strip(["hel?llo","intro"])
    ['helllo', 'intro']