how can I remove punctuation from a string in python

Discussion in 'Python' started by earlwindler, Jan 12, 2021.

  1. earlwindler

    earlwindler New Member

    Joined:
    Jan 11, 2021
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Location:
    United States
    Home Page:
    http://codeleaks.io/
    For Example

    s = "AAA? BBB. CCC!"

    So, I do:

    import string
    table = str.maketrans('', '', string.punctuation)
    s = [w.translate(table) for w in s]

    And it's all right. My new sentence will be:

    s = "AAA BBB CCC"

    But, if I have input sentence like:

    s = "AAA? BBB. CCC! DDD.EEE"

    after remove punctuation the same method as below I'll have

    s = "AAA BBB CCC DDDEEE"

    but need:

    s = "AAA BBB CCC DDD EEE"

    Is any ideas/methods how to solve this problem?
     
  2. marblete

    marblete New Member

    Joined:
    May 17, 2021
    Messages:
    3
    Likes Received:
    3
    Trophy Points:
    3
    Gender:
    Male
    I think I have a solution

    Code:
    import string
    
    def replace_punct(inp):
        s = ''
    
        for i in range(len(inp)):
            if inp[i] in string.punctuation:
                if inp[i+1] == ' ':
                    s += ''
                else:
                    s += ' '
            else:
                s += inp[i]
        return s
    
    thestring = 'AAA? BBB. CCC! DDD.EEE'
    
    print('Input: ',thestring)
    print('Output: ',replace_punct(thestring))
    
    Output:
    Code:
    ~/Documents/Python$ python3 scratch.py 
    Input:  AAA? BBB. CCC! DDD.EEE
    Output:  AAA BBB CCC DDD EEE
    
    Hope it helps!
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice