【问题标题】:Is there a way to remove punctuation at the start and end of each word in string but not the middle? Python [closed]有没有办法删除字符串中每个单词的开头和结尾的标点符号而不是中间的标点符号? Python [关闭]
【发布时间】:2020-07-03 13:45:28
【问题描述】:
编写一个函数 beautify_sentence(sentence, punctuation),它返回一个新句子(类型字符串),从单词中删除所有指定的标点符号(单词由空格分隔)。
例如,句子“?hello !mango! and, ban,ana yum apple!”使用标点符号“?!”将导致返回字符串“hello mango and ban,ana yum apple”。
注意“ban,ana”仍然包含逗号。
【问题讨论】:
标签:
python
string
list
methods
punctuation
【解决方案1】:
这是一个开始的好地方。在香蕉中留下逗号会有点棘手。将来,我建议发布您对代码的尝试,即使您认为它很粗糙。以这种方式引导您朝着正确的方向前进要容易得多。祝你好运!
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!', '?!,'))
【解决方案2】:
这应该为你做。
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