Python Forum

Full Version: Set Comprehension
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a text file that is going to be sent to my function. I simply need to send the words in the file back in a set. Not so difficult with a for loop. My for loop is like this:

#the text file is sent to my function. This is the only code in it.
for w in text.split():
      w.strip(punctuation)
      cypher.add(w)
print(cypher)
return cypher
The print statement is just so I can test it and make sure I did it right. This works just fine and I return the words. I need them in a set using set comprehension. I'm missing something and I'm trying to put my for loop into a comprehension, but don't know how. I've looked at multiple examples but can't figure out what I'm doing wrong. 

When I try to do it with a set comprehension, I'm doing this:
#The text file is sent to my function. Only code is below:
cypher = set()
cypher = {text.strip(punctuation()) for w in text.split()}
return cypher
Thanks for any help.
I am not sure if there is something like set comprehension.
You can use list comprehension and set() it.
sypher = set([w.strip(punctuation) for w in text(split)])
Just use your original set comprehension with first "text" replaced with "w" and without "()" after punctuation, as wavic posted.
cypher = {w.strip(punctuation) for w in text.split()}
String methods do not work in-place, so your original for loop did not remove punctuation at all.
Thank you.