I am trying to print out the contents of a set and when I do, I get the set identifier in the print output. For example, this is my output set(['a', 'c', 'b', 'e', 'd', 'f', 'gg', 'ff', 'jk'])
" for the code below. I want to get rid of the word set
. My code is very simple and is below.
infile = open("P3TestData.txt", "r")
words = set(infile.read().split())
print words
Here is my output again for easy reference: set(['a', 'c', 'b', 'e', 'd', 'f', 'gg', 'ff', 'jk'])
The
print
statement usesset
's implementation of__str__()
. You can:Roll out your own printing function, instead of using
print
. A simple way to get a nicer formatting may be to uselist
's implementation of__str__()
instead:print list(my_set)
Override the
__str__()
implementation in your ownset
subclass.This subclass works for numbers and characters:
outputs
You can do this if you want the curly braces:
Or, use format:
If printing a set of numbers in Python 3, you can alternatively use slicing.
This doesn't translate well when porting back to Python2...
On the other hand, to
join()
integer values you have to convert to string first:This is still more correct than slicing, however.
You could convert the set to a list, just for printing:
or you could use
str.join()
to join the contents of the set with a comma: