Search code examples
pythonstringreplacebigdatapunctuation

replace all punctuation in string with another string in python


i want to replace all punctuation with string "PUNCTUATION"

. I have many long string , so i need an efficient code.

for example i have some string like this

s = "Hello. World, Awesome! Really?"

i want the output to become something like this

replaced_s = "Hello PUNCTUATION World PUNCTUATION Awesome PUNCTUATION Really PUNCTUATION"

i think i can use replace but wont it take too long? any solution for this?


Solution

  • Try the string.punctuation

    import string
    s = "Hello. World, Awesome! Really?"
    for c in string.punctuation:
        s = s.replace(c,' PUNCTUATION ')
    s
    #'Hello PUNCTUATION  World PUNCTUATION  Awesome PUNCTUATION  Really PUNCTUATION '
    

    Or use regex:

    import re
    s = "Hello. World, Awesome! Really?"
    s = re.sub(r'[^\w\s]',' PUNCTUATION ',s)
    re.sub(' +', ' ',s)
    #'Hello PUNCTUATION World PUNCTUATION Awesome PUNCTUATION Really PUNCTUATION '