以下是一个不使用正则表达式的解决方法,使用Python的字符串操作来删除字符串中的标点符号和空格:
import string
def remove_punctuation_and_spaces(text):
    # 删除标点符号
    text = text.translate(str.maketrans('', '', string.punctuation))
    # 删除空格
    text = text.replace(" ", "")
    return text
# 示例用法
text = "Hello, World! This is a sentence with punctuation and spaces."
clean_text = remove_punctuation_and_spaces(text)
print(clean_text)
输出:
HelloWorldThisisasentencewithpunctuationandspaces
该方法使用translate()函数和maketrans()方法来删除标点符号。string.punctuation包含了所有的标点符号字符,str.maketrans()将这些字符映射为空字符。然后,使用replace()函数来删除空格。
请注意,该方法只能删除ASCII标点符号和空格。对于非ASCII字符和其他特殊字符,您可能需要使用更复杂的方法。
下一篇:不使用正则表达式来替换整个单词