how to ignore punctuation when counting characters in string in python

Viewed 3307

In my homework there is question about write a function words_of_length(N, s) that can pick unique words with certain length from a string, but ignore punctuations.

what I am trying to do is:

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.  

so my problem is that I don't know how to remove punctuation , I did view "best way to remove punctuation from string" and relevant questions, but those looks too difficult in my lvl and also because my teacher requires it should contain no more than 2 lines of code.

sorry that I can't edit my code in question properly, it's first time i ask question here, there much i need to learn, but pls help me with this one. thanks.

3 Answers

First of all, you need to create a new string without characters you want to ignore (take a look at string library, particularly string.punctuation), and then split() the resulting string (sentence) into substrings (words). Besides that, I suggest using type annotation, instead of comments like those.

def words_of_length(n: int, s: str) -> list:
    return [x for x in ''.join(char for char in s if char not in __import__('string').punctuation).split() if len(x) == n]

>>> words_of_length(3, 'Guido? van, rossum. is the best!'))
['van', 'the']

Alternatively, instead of string.punctuation you can define a variable with the characters you want to ignore yourself.

You can remove punctuation by using string.punctuation.

>>> from string import punctuation
>>> text = "text,. has ;:some punctuation."
>>> text = ''.join(ch for ch in text if ch not in punctuation)
>>> text # with no punctuation
'text has some punctuation'
Related