2017-11-18 1303 views
0

我需要一些更多的帮助。基本上,我试图返回删除所有非空格和非字母数字字符的用户输入。我做了这么多的代码,但我不断收到错误...如何从字符串中删除标点符号? (Python)

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 = '''''!()-[]{};:'"\,<>./[email protected]#$%^&*_~''' 
    my_str = s 
    no_punct = "" 
    for char in my_str: 
     if char not in punctuation: 
      no_punct = no_punct + char 
    return(no_punct) 

我不知道我在做什么错。任何帮助表示赞赏!

+0

请描述或发布错误。没有人可以帮助你,否则 – ytpillai

+1

所有这些引号是怎么回事?尝试更类似于''!() - [] {};:\'“\,<> ./[email protected]#$%^&*_〜'' –

+0

”Python Shell,提示2,第1行 语法错误:无效的语法:,第1行,第31位“是我的特定错误 –

回答

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) 
+0

感谢您的快速回答,但是当我尝试评估它时,会发生以下情况: >>> remove_punctuation(“您好,我一定要去!”) 回溯(最近呼叫最后一次): Python Shell,prompt 2,line 1 文件“C:/ Users/Marquela Nunes/Desktop/Test Python.py”,第8行,在 new_s = [i for i in s if i.isalnum()or i .isalpha()] builtins.NameError:name's'is not defined –

+0

这也删除空格 – James

+0

@MarquelaNunes当你像这样调用'remove_punctuation'时,你应该得到一个参数remove_punctuation('hello,asdns') –

0

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

import re 

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

谢谢!我不确定在这个任务中是否允许使用正则表达式模块,但我会记住以防万一! –

0

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

s="This is a String with Punctuations [email protected]@$##%" 
    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

+0

谢谢,我会阅读。 –

+0

我改变了链接....到最新版本的python ...阅读此链接 –

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 = "!()-[]{};:'\"\,<>./[email protected]#$%^&*_~" 
    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("!()-[]{};:'\"\,<>./[email protected]#$%^&*_~") 
print("Result 2: ", result) 
相关问题