Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何解决在Python中用空字符替换sharp字符的问题?_Python_String_Replace - Fatal编程技术网

如何解决在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