原文: https://www.programiz.com/python-programming/examples/remove-punctuation

该程序从字符串中删除所有标点符号。 我们将使用for循环检查字符串的每个字符。 如果字符是标点符号,则为它分配一个空字符串。

要理解此示例,您应该了解以下 Python 编程主题:


有时,我们可能希望将一个句子分成单词列表。

在这种情况下,我们可能首先要清理字符串并删除所有标点符号。 这是一个如何完成的示例。

源代码

  1. # define punctuation
  2. punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
  3. my_str = "Hello!!!, he said ---and went."
  4. # To take input from the user
  5. # my_str = input("Enter a string: ")
  6. # remove punctuation from the string
  7. no_punct = ""
  8. for char in my_str:
  9. if char not in punctuations:
  10. no_punct = no_punct + char
  11. # display the unpunctuated string
  12. print(no_punct)

输出

  1. Hello he said and went

在此程序中,我们首先定义一个标点符号字符串。 然后,我们使用for循环遍历提供的字符串。

在每次迭代中,我们使用隶属关系测试检查字符是否为标点符号。 我们有一个空字符串,如果不是标点符号,我们会向其添加(连接)该字符。 最后,我们显示清理后的字符串。