2

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.

adder
  • 3,512
  • 1
  • 16
  • 28
burger j
  • 23
  • 1
  • 4

3 Answers3

1

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

In you function replace x with strip (x, ['.', ',', ':', ';', '!', '?']

Add more punctuation if needed

Thomas
  • 1,026
  • 7
  • 18
  • thank you so much for replay my question so soon, i add x = str.strip(x,[',','.']) in the middle line, but it shows me "local variable 'x' referenced before assignment" – burger j Oct 06 '17 at 02:56
  • It should be return [split (x, ...) for x in s if len(split (x,...)) == N] – Thomas Oct 06 '17 at 03:00
  • Sorry I made a mistake it should read [strip (x, ...) for x in s.split () if len(strip (x,...)) == N] – Thomas Oct 06 '17 at 03:29
0

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.

adder
  • 3,512
  • 1
  • 16
  • 28
  • thank you so much for helping me out, i test this code on jupyter notebooks, it works perfect, but i do have some question about " ' '.join( ) ", is that what you said about creat a new string? – burger j Oct 06 '17 at 03:03
  • `''` is an empty string. Yes, that's what I meant by *create a new string*. – adder Oct 06 '17 at 03:06
0

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'
srikavineehari
  • 2,502
  • 1
  • 11
  • 21