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'])
You could convert the set to a list, just for printing:
print list(words)
or you could use str.join()
to join the contents of the set with a comma:
print ', '.join(words)
The print
statement uses set
'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 use list
's implementation of __str__()
instead:
print list(my_set)
Override the __str__()
implementation in your own set
subclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With