2017-11-18 1304 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) 
相關問題