Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing set identifier when printing sets in Python

Tags:

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

like image 496
johns4ta Avatar asked Mar 10 '13 22:03

johns4ta


2 Answers

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) 
like image 128
Martijn Pieters Avatar answered Oct 12 '22 23:10

Martijn Pieters


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.

like image 28
slezica Avatar answered Oct 13 '22 00:10

slezica