简体   繁体   中英

Changing Punctuation to White space(space character)

As of now it takes the punctuation out, but I cannot figure out how to make it add a space instead of just taking out the punctuation. Currently I have:

punctuation = "!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~"
def remove_punct(theStr):
    theStr_sans_punct = ""
    for letter in theStr:
        if letter not in punctuation:
            theStr_sans_punct = theStr_sans_punct + letter
    return theStr_sans_punct

It's in a interactive textbook so it will automatically do the tests on their site.

By adding an else to your code:

punctuation = "!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~"
def remove_punct(theStr):
    theStr_sans_punct = ""
    for letter in theStr:
        if letter not in punctuation:
            theStr_sans_punct = theStr_sans_punct + letter
        else:
            theStr_sans_punct = theStr_sans_punct + " "
return theStr_sans_punct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM