Python – 从给定的字符串中去除前后标点符号
给定一个字符串带前后标点符号。
Input : test_str = ‘%$Gfg is b!!est(*^’
Output : Gfg is b!!est
Explanation : Front and rear punctuations are stripped.
Input : test_str = ‘%Gfg is b!!est(*^’
Output : Gfg is b!!est
Explanation : Front and rear punctuations are stripped.
方法#1:使用标点符号()+循环
在此,我们使用 punctuation() 来检查标点符号,从后面和前面,一次,找到非 pnc char,记录索引并拆分字符串。
Python3
# Python3 code to demonstrate working of
# Strip Punctuations from String
# Using loop + punctuation
from string import punctuation
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
# printing original string
print("The original string is : " + str(test_str))
# getting first non-pnc idx
frst_np = [idx for idx in range(len(test_str)) if test_str[idx] not in punctuation][0]
# getting rear non-pnc idx
rear_np = [idx for idx in range(len(test_str) - 1, -1, -1) if test_str[idx] not in punctuation][0]
# spittd string
res = test_str[frst_np : rear_np + 1]
# printing result
print("The stripped string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Strip Punctuations from String
# Using strip() + split() + join()
from string import punctuation
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
# printing original string
print("The original string is : " + str(test_str))
# strip is used to remove rear punctuations
res = ' '.join([ele.strip(punctuation) for ele in test_str.split()])
# printing result
print("The stripped string : " + str(res))
输出
The original string is : %$Gfg is b!!est(*^&*
The stripped string : Gfg is b!!est
方法 #2:使用 strip() + split() + join()
在此,我们使用 split() 执行拆分任务,以获取单个单词,strip() 用于删除标点符号。最后 join() 用于执行单词的连接。
Python3
# Python3 code to demonstrate working of
# Strip Punctuations from String
# Using strip() + split() + join()
from string import punctuation
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
# printing original string
print("The original string is : " + str(test_str))
# strip is used to remove rear punctuations
res = ' '.join([ele.strip(punctuation) for ele in test_str.split()])
# printing result
print("The stripped string : " + str(res))
输出
The original string is : %$Gfg is b!!est(*^&*
The stripped string : Gfg is b!!est