您应该regex
为此使用:
>>> import re
>>> from string import punctuation as punc
>>> strs = "Abc*@ddf%^sad#"
>>> re.sub(r'[{}]'.format(punc),'',strs)
'Abcddfsad'
修复您的代码:
>>> jobLocationUnclean = 'Abc*@ddf%sad#'
>>> for c in "!@#%&*()[]{}/?<>,.":
#re-assign the new string to the `jobLocationUnclean`
jobLocationUnclean = jobLocationUnclean.replace(c, "")
>>> jobLocationUnclean
'Abcddfsad'
为什么你的代码失败了?
在您的代码中,您正在遍历这些标点符号并分配jobLocationUnclean
to的替换值jobLocationCleaned
,但请注意字符串在 python 中是不可变的,因此replace(jobLocationUnclean, c, "")
操作根本不会更改原始值jobLocationUnclean
。因此,在每次迭代中,您都会替换给定的标点符号并将新字符串分配给jobLocationCleaned
. 对字符串的任何操作总是返回一个新字符串。
>>> strs = "foo"
>>> strs.replace('f','i')
'ioo'
>>> strs #original foo is still un-changed
'foo'
所以最后你的代码实际上只替换.
了 string( jobLocationUnclean
) 中的字符并将其分配给jobLocationCleaned
.