Python代码 在线执行

Python 程序:从字符串中删除标点符号

/examples/remove-punctuation

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

要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:


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

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

源代码

# 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循环遍历提供的字符串。

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