Removing set identifier when printing sets in Pyth

2019-01-14 06:59发布

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

5条回答
ら.Afraid
2楼-- · 2019-01-14 07:39

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.

查看更多
Luminary・发光体
3楼-- · 2019-01-14 07:48

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
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-14 07:49

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}
查看更多
The star\"
5楼-- · 2019-01-14 07:58

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.

查看更多
Evening l夕情丶
6楼-- · 2019-01-14 08:06

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)
查看更多
登录 后发表回答