用于从字符串中删除标点符号的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


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

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

源代码

# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user
# my_str = input("Enter a string: ")

# remove punctuation from the string
no_punct = ""
for char in my_str:
   if char not in punctuations:
       no_punct = no_punct + char

# display the unpunctuated string
print(no_punct)

输出

Hello he said and went

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

在每次迭代中,我们使用成员资格测试来检查该字符是否为标点符号。我们有一个空字符串,如果字符不是标点符号,我们就将它添加(连接)到这个空字符串中。最后,我们显示清理后的字符串。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战