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.
You can do this if you want the curly braces:
>>> s={1,2,3}
>>> s
set([1, 2, 3])
>>> print list(s).__str__().replace('[','{').replace(']','}')
{1, 2, 3}
Or, use format:
>>> print '{{{}}}'.format(', '.join(str(e) for e in set([1,'2',3.0])))
{3.0, 1, 2}
If printing a set of numbers in Python 3, you can alternatively use slicing.
Python 3.3.5
>>> s = {1, 2, 3, 4}
>>> s
{1, 2, 3, 4}
>>> str(s)[1:-1]
'1, 2, 3, 4'
This doesn't translate well when porting back to Python2...
Python 2.7.6
>>> s = {1, 2, 3, 4}
>>> str(s)[1:-1]
'et([1, 2, 3, 4]'
>>> str(s)[5:-2]
'1, 2, 3, 4'
On the other hand, to join()
integer values you have to convert to string first:
Python 2.7.6
>>> strings = {'a', 'b', 'c'}
>>> ', '.join(strings)
'a, c, b'
>>> numbers = {1, 2, 3, 4}
>>> ', '.join(numbers)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> ', '.join(str(number) for number in numbers)
'1, 2, 3, 4'
This is still more correct than slicing, however.
This subclass works for numbers and characters:
class sset(set):
def __str__(self):
return ', '.join([str(i) for i in self])
print set([1,2,3])
print sset([1,2,3])
outputs
set([1, 2, 3])
1, 2, 3