Q:

Punctuation Replacement Python

Learning python and can't seem to figure out why my code doesn't work, I'm trying to replace all punctuation in a given string with a space. Here's my code...
import string 

def replace(text):

    for char in text:
        if char in string.punctuation:
            text.replace(char, " ")

    return text 

test = "Ok! Where, to now?"

#expected "Ok  Where  to now  " 
#returned "Ok! Where to now?" 

Any input is appreciated! Thanks!

A:

replace doesn't modify the string passed into the first argument (string objects are immutable, meaning the object itself can't be modified). So you'll need to update the text variable with the return value of the replace operation yourself:
text = text.replace(char, " ")

From the documentation (emphasis mine):

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

