How Do You Remove Punctuation From A String? (Python)

2.7k views Asked by At

I need some more help. Basically, I'm trying to return the user input with all non-space and non-alphanumeric characters removed. I made code for this much of the way, but I keep getting errors...

def remove_punctuation(s):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric  
    characters removed. 
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''   
    punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''  
    my_str =  s 
    no_punct = ""  
    for char in my_str:  
        if char not in punctuation:  
            no_punct = no_punct + char  
    return(no_punct)  

I'm not sure what I'm doing wrong. Any help is appreciated!

4

There are 4 answers

8
Frank AK On BEST ANSWER

I guess that's will work for you !

def remove_punctuation(s):
    new_s = [i for i in s if i.isalnum() or i.isalpha() or i.isspace()]
    return ''.join(new_s)
0
John Hanley On

I added the space character to your punctuation string and cleanup up your use of quotes in the punctuation string. Then I cleaned up the code in my own style so that can see the small differences.

def remove_punctuation(str):
    '''(str) -> str
    Return s with all non-space or non-alphanumeric
    characters removed.
    >>> remove_punctuation('a, b, c, 3!!')
    'a b c 3'
    '''
    punctuation = "! ()-[]{};:'\"\,<>./?@#$%^&*_~"
    no_punct = ""
    for c in str:
        if c not in punctuation:
            no_punct += c
    return(no_punct)

result = remove_punctuation('a, b, c, 3!!')
print("Result 1: ", result)
result = remove_punctuation("! ()-[]{};:'\"\,<>./?@#$%^&*_~")
print("Result 2: ", result)
1
James On

Can you use the regular expression module? If so, you can do:

import re

def remove_punctuation(s)
    return re.sub(r'[^\w 0-9]|_', '', s)
0
MOHAMMED NUMAN On

There is an inbuilt function to get the punctuations...

    s="This is a String with Punctuations !!!!@@$##%"
    import string
    punctuations = set(string.punctuations)
    withot_punctuations = ''.join(ch for ch in s if ch not in punctuations)

You will get the string without punctuations

output:
This is a String with Punctuations

You can find more about string functions here