Search code examples
pythonstringlistmethodspunctuation

Is there a way to remove punctuation at the start and end of each word in string but not the middle? Python


write a function beautify_sentence(sentence, punctuation) which returns a new sentence (type string) that removes all the specified punctuations from words (words are separated by a white space).

For example, sentence "?hello !mango! and, ban,ana yum apple!" with punctuation "?!," would result in returning a string "hello mango and ban,ana yum apple".

Notice that "ban,ana" still contains comma.


Solution

  • This should do it for you.

    from string import punctuation
    
    a="""'?hello !mango! and, ban,ana yum apple!',  '?!,' """
    new=[i.strip(punctuation) for i in a.split()]
    print(" ".join(new))
    

    output:

    hello mango and ban,ana yum apple