23

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'])

4

5 回答 5

52

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)
于 2013-03-10T22:59:26.940 回答
3

The print statement uses set's implementation of __str__(). You can:

  1. 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)

  2. Override the __str__() implementation in your own set subclass.

于 2013-03-10T23:01:57.557 回答
2

这个子类适用于数字和字符:

class sset(set):
    def __str__(self):
        return ', '.join([str(i) for i in self])

print set([1,2,3])
print sset([1,2,3])

输出

set([1, 2, 3])
1, 2, 3
于 2015-05-01T00:45:52.207 回答
1

如果你想要花括号,你可以这样做:

>>> s={1,2,3}
>>> s
set([1, 2, 3])
>>> print list(s).__str__().replace('[','{').replace(']','}')
{1, 2, 3}

或者,使用格式:

>>> print '{{{}}}'.format(', '.join(str(e) for e in set([1,'2',3.0])))
{3.0, 1, 2}
于 2013-03-11T00:56:21.390 回答
1

如果在 Python 3 中打印一组数字,您也可以使用切片。

Python 3.3.5
>>> s = {1, 2, 3, 4}
>>> s
{1, 2, 3, 4}
>>> str(s)[1:-1]
'1, 2, 3, 4'

这在移植回 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'

另一方面,对于join()整数值,您必须先转换为字符串:

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'

然而,这仍然比切片更正确。

于 2014-06-18T14:08:10.987 回答