Skip to main content
 首页 » 编程设计

python之在python中计算字符串中的字符时如何忽略标点符号

2025年02月15日18lyhabc

在我的家庭作业中,有一个关于编写函数 words_of_length(N, s) 的问题,该函数可以从字符串中选择具有特定长度的唯一单词,但忽略标点符号。

我想做的是:

def words_of_length(N, s):     #N as integer, s as string   
    #this line i should remove punctuation inside the string but i don't know how to do it   
    return [x for x in s if len(x) == N]   #this line should return a list of unique words with certain length.   

所以我的问题是我不知道如何删除标点符号,我确实查看了“从字符串中删除标点符号的最佳方法”和相关问题,但这些在我的等级中看起来太难了,而且因为我的老师要求它应该包含不超过 2 行代码。

抱歉,我无法正确编辑我的问题代码,这是我第一次在这里提问,我需要学习很多东西,但请帮助我解决这个问题。谢谢。

请您参考如下方法:

使用 string.strip(s[, chars]) https://docs.python.org/2/library/string.html

在你的函数中用 strip 替换 x (x, ['.', ',', ':', ';', '!', '?']

如果需要,添加更多标点符号