如何解决在Python中用空字符替换sharp字符的问题?
我有一个类似这样的代码:如何解决在Python中用空字符替换sharp字符的问题?,python,string,replace,Python,String,Replace,我有一个类似这样的代码: punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] def strip_punctuation(str_word): for char in str_word: if char in punctuation_chars:
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(str_word):
for char in str_word:
if char in punctuation_chars:
new_word = str_word.replace(char,'')
return new_word
print(strip_punctuation("#inc.red.ible"))
这是输出:
#incredible
incredible
例如,在上面的代码中,我无法通过replace方法删除sharp字符或@char。我想知道为什么只有这些字符才会出现这种情况。您好,我认为这应该可以解决您的问题:
def strip_punctuation(str_word):
for char in str_word:
if char in punctuation_chars:
str_word = str_word.replace(char,'')
return str_word
您每次都会阅读
str\u word
,即使您已经进行了其他修改并将其保存到new\u word
中。确保对同一字符串应用连续修改。例如:
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(str_word):
for char in str_word:
if char in punctuation_chars:
str_word = str_word.replace(char,'')
return str_word
print(strip_punctuation("#inc.red.ible"))
你可以用正则表达式的强大功能来解决这个问题 使用内置模块中的方法: 输出:
incredible