如何解决如何解决用Python中的空字符替换尖锐字符的问题?
我有这样的代码:
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
例如,在上面的代码中,我无法通过replace方法删除该尖锐char或@ char。我不知道为什么只在这些字符上才会发生这种情况。
解决方法
即使您已经进行了其他修改并将其保存到str_word
中,您也每次都从new_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"))
,
嗨,我认为这应该可以解决您的问题:
def strip_punctuation(str_word):
for char in str_word:
if char in punctuation_chars:
str_word = str_word.replace(char,'')
return str_word
,
您可以使用正则表达式解决此问题!
import re
punctuation_chars = ["'",'@']
def strip_punctuation(str_word):
return re.sub('\\'+'|\\'.join(punctuation_chars),'',str_word)
print(strip_punctuation("#inc.red.ible"))
输出:
incredible
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。