2017-09-30 9 views
-1

この関数では、このコードでのみコードが機能しますが、すべての例で機能しない理由はわかりません。誰でも助けてくれますか?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' 
    ''' 
    new_str = '' 
    for char in s: 
     if char.isdigit() or char.isalpha(): 
      new_str = new_str + char + " " 
    new_s = new_str[:len(new_str)-1] 
    return new_s 

ここに私のものがあります。

により、このラインに
+0

私はすべての例と例のために、この機能を動作させるにはどうすればよいですか? – dg123

+0

動作しないサンプルを投稿すると便利です。 – mhawke

答えて

0

new_str = new_str + char + " " 

あなたのコードは、常に各保存文字の後にスペースを追加します。したがって、英数字の実行は、間にスペースを入れてしまいます。

機能が動作しない別の例は、文字列内に複数のスペースがある場合です(例: 'a, b, c, 3!! '。あなたの説明によれば、スペースは保存されるべきです。

あなたの関数は、文字が空白かどうかをisspace()で確認することもできます。あなただけ、あなたはchar == ' 'char.isspace()を置き換えることができ空白文字を保持したい場合は

 
'a b c 3' 
'a b c 3' 

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' 
    ''' 
    new_str = '' 
    for char in s: 
     if char.isalnum() or char.isspace(): 
      new_str = new_str + char 
    return new_str 

print(repr(remove_punctuation('a, b, c, 3!!'))) 
print(repr(remove_punctuation('a, b, c, 3!!'))) 

出力:これは、空白文字だけでなく、タブ、改行などが含まれます。ここで


str.join()を使用して、文字列、リスト内包表記/ジェネレータ式から文字を削除する一般的な方法である:

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' 
    ''' 
    return ''.join(c for c in s if c.isalnum() or c.isspace()) 
関連する問題