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

编写一个Python程序,从字符串中移除标点符号。我们声明了一个包含可能标点符号的字符串,并使用for循环迭代给定的文本。

在此示例中,if语句将每个字符与标点符号进行比较,如果未找到,则该字符将被赋给一个新字符串,从而移除标点符号。

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

orgStr = "Hi!!, Welcome, Tutorial-Gateway?"

newStr = ""

for char in orgStr:
    if char not in punctuations:
        newStr = newStr + char

print("\nThe Original String Before Removing Punctuations")
print(orgStr)

print("\nThe Final String After Removing Punctuations")
print(newStr)
Program to Remove Punctuations from a String

此程序允许用户输入一个字符串并从中移除标点符号。

orgStr = input("Please Enter Any String = ")

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

newStr = ""

for char in orgStr:
    if char not in punctuations:
        newStr = newStr + char

print("\nBefore Removing")
print(orgStr)

print("\nAfter Removing")
print(newStr)
Please Enter Any String = Learn@#&^%$# Python<>? Programs?

Before Removing
Learn@#&^%$# Python<>? Programs?

After Removing
Learn Python Programs

下面的程序使用while循环帮助从字符串中移除标点符号。

orgStr = input("Please Enter Any Text = ")

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

newStr = ""

i = 0
while i < len(orgStr):
    if orgStr[i] not in punctuations:
        newStr = newStr + orgStr[i]
    i = i + 1

print("\nBefore Removing")
print(orgStr)

print("\nTAfter Removing")
print(newStr)
Please Enter Text = hi!!@ tutorial @@#&^ gateway {}\ followers

Before Removing 
hi!!@ tutorial @@#&^ gateway {}\ followers

After Removing
hi tutorial  gateway  followers