如何从字符串中删除标点符号? (蟒蛇)

时间:2017-11-18 02:10:21

标签: python string loops

我还需要一些帮助。基本上,我试图返回用户输入,删除所有非空格和非字母数字字符。我为此做了很多代码,但我一直都有错误......

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)  

我不确定我做错了什么。任何帮助表示赞赏!

4 个答案:

答案 0 :(得分:0)

我想这对你有用!

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

答案 1 :(得分:0)

您可以使用正则表达式模块吗?如果是这样,你可以这样做:

import re

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

答案 2 :(得分:0)

  

有一个内置函数来获取标点符号...

    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)

您将获得没有标点符号的字符串

output:
This is a String with Punctuations

You can find more about string functions here

答案 3 :(得分:0)

我在你的标点符号字符串中添加了空格字符,并清除了标点字符串中引号的使用。然后我用我自己的风格清理了代码,这样可以看出差异很小。

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)