Python 试图从字符串中删除所有标点字符,但我一直保留的所有内容//都保留在

Python 试图从字符串中删除所有标点字符,但我一直保留的所有内容//都保留在,python,python-3.6,Python,Python 3.6,我正在尝试编写一个函数来删除字符串中的所有标点字符。我在翻译、替换、剥离等方面尝试了几种排列。我最近的尝试使用了蛮力方法: def clean_lower(sample): punct = list(string.punctuation) for c in punct: sample.replace(c, ' ') return sample.split() 这就去掉了几乎所有的标点符号,但我在其中一个单词的前面留下了//。我似乎找不到任何方法来移除它。

我正在尝试编写一个函数来删除字符串中的所有标点字符。我在翻译、替换、剥离等方面尝试了几种排列。我最近的尝试使用了蛮力方法:

def clean_lower(sample):
    punct = list(string.punctuation)
    for c in punct:
        sample.replace(c, ' ')
    return sample.split()
这就去掉了几乎所有的标点符号,但我在其中一个单词的前面留下了//。我似乎找不到任何方法来移除它。我甚至尝试过用sample.replace('/','')显式替换它。
我需要做什么?

使用正则表达式

import re
def clean_lower(s):
    return(re.sub(r'\W','',s))

上述函数使用
translate
删除下划线以外的任何符号,这是删除标点符号的最快方法,这也将删除
/

import string 

s = "This is! a string, with. punctuations? //"

def clean_lower(s):
    return s.translate(str.maketrans('', '', string.punctuation))

s = clean_lower(s)
print(s)

也许你应该从你想保留什么的角度来看待它:

例如:

import string

toKeep   = set(string.ascii_letters + string.digits + " ")
toRemove = set(string.printable) - toKeep
cleanUp  = str.maketrans('', '', "".join(toRemove))
用法:

s = "Hello! world of / and dice".translate(cleanUp)

# s will be 'Hello world of  and dice'

正如@jasonharper所建议的,您需要重新定义“sample”,它应该可以工作:

import string 

sample='// Hello?) // World!'
print(sample)

punct=list(string.punctuation)

for c in punct:
    sample=sample.replace(c,'')

print(sample.split())

请发帖。@rpoleski我相信他给了我们一个最小的,可复制的例子。这个问题出了什么问题?显示一个产生错误输出的输入。还要定义什么是
string
。//不是标点符号,所以您是否尝试删除任何符号假设
sample
是字符串,
sample.replace(c.),
完全不做任何事情-您创建了一个新字符串,但随后将其丢弃,而不是将其分配回变量。