是否有一种方法可以删除字符串中每个单词的开头和结尾的标点符号,但不能删除中间的标点符号? Python [关闭]

问题描述 投票:-6回答:2

编写一个函数beautify_sentence(sentence,标点符号),该函数返回一个新句子(类型字符串),该句子从单词中删除所有指定的标点符号(单词之间用空格隔开)。

例如,句子“?hello!mango !,然后,禁令你要吃的苹果!”标点符号为“?!”的结果将返回字符串“ hello mango and ban,ana yum apple”。

注意“ ban,ana”仍然包含逗号。

python string list methods punctuation
2个回答
0
投票

这应该为您做。

from string import punctuation

a="""'?hello !mango! and, ban,ana yum apple!',  '?!,' """
new=[i.strip(punctuation) for i in a.split()]
print(" ".join(new))

输出:

hello mango and ban,ana yum apple

0
投票

这里是入门的好地方。将逗号放在香蕉上会比较棘手。将来,即使您认为这很粗糙,我也建议您发布对代码的尝试。以这种方式引导您朝正确的方向容易得多。祝你好运!

import string

def beautify_sentence(sentence, punctuation):
        beautiful = sentence.translate(str.maketrans('', '', string.punctuation))
        return beautiful

print(beautify_sentence('?hello !mango! and, ban,ana yum apple!',  '?!,'))
© www.soinside.com 2019 - 2024. All rights reserved.