Python|从字符串中删除标点符号
很多时候,在处理Python字符串时,我们都会遇到需要从字符串中删除某些字符的问题。这可以应用于数据科学领域的数据预处理以及日常编程。让我们讨论一下我们可以执行此任务的某些方法。
方法#1:使用循环+标点字符串
这是可以执行此任务的粗暴方式。在此,我们使用包含标点符号的原始字符串检查标点符号,然后构建删除这些标点符号的字符串。
Python3
# Python3 code to demonstrate working of
# Removing punctuations in string
# Using loop + punctuation string
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# initializing punctuations string
punc = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# Removing punctuations in string
# Using loop + punctuation string
for ele in test_str:
if ele in punc:
test_str = test_str.replace(ele, "")
# printing result
print("The string after punctuation filter : " + test_str)
Python3
# Python3 code to demonstrate working of
# Removing punctuations in string
# Using regex
import re
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# Removing punctuations in string
# Using regex
res = re.sub(r'[^\w\s]', '', test_str)
# printing result
print("The string after punctuation filter : " + res)
输出 :
The original string is : Gfg, is best : for ! Geeks ;
The string after punctuation filter : Gfg is best for Geeks
方法#2:使用正则表达式
用标点符号替换的部分也可以使用正则表达式来执行。在此,我们使用某个正则表达式将所有标点符号替换为空字符串。
Python3
# Python3 code to demonstrate working of
# Removing punctuations in string
# Using regex
import re
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# Removing punctuations in string
# Using regex
res = re.sub(r'[^\w\s]', '', test_str)
# printing result
print("The string after punctuation filter : " + res)
输出 :
The original string is : Gfg, is best : for ! Geeks ;
The string after punctuation filter : Gfg is best for Geeks