sarat
sarat

Reputation: 11120

Python: concatinating the string output

I have class which holds a an integer and another list holds the data.

class Vertex:
    def __init__(self, ID = str()):
        self.id = ID
        self.neighbors = AdjacencyList()

Adjacency list is another class. which holds a list.

I would to print the id and the list in the neighbors with a single print statement. How it's possible?

This is the code I use right now (employing string concatenation)

def printGraph(g = Graph()):
    msg = str('')
    for k, v in g.nodes.iteritems():
        root_node = g.nodes[k]
        msg = "(" + k + " , " + str(root_node.color) + ") : "

        for x in v.neighbors.innerlist:
            msg += str(x.id) + " , "
        print msg

You can see the whole string separators I used in the print method.

Upvotes: 0

Views: 165

Answers (4)

Vicent
Vicent

Reputation: 5452

I think your code can be rewritten as follows:

def printGraph(g = Graph()):
    for k, v in g.nodes.iteritems():
        msg = "({0} , {1}) : {2}".format(k, v.color, ", ".join(["{0}".format(x.id) for x in v.neighbors.innerlist]))
        print msg

As you see, the trick for building the whole string in just one step is to replace the last for loop with a list comprehension which is, in place, converted into a string and included in the initial string. This way you print the list items individually instead of printing the list object so you can:

  • give the desired output format to items
  • print items attributes

Upvotes: 1

volcano
volcano

Reputation: 3582

I did not test it - and it's sort of unreadable, but in one line it should be something like

print '\n'.join(('({},{}):{}'.format(key, node.color,
                                     ','.join('{}'.format(x) for x in node.neighbors.innerlist)) 
                for key, node in g.nodes.iteritems())

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213223

You can use str.format() function to format your output: -

print "Id: {0}, Neighbour: {1}".format(self.id, self.neighbours)

This will work in Python 2.6+. For older version, you might need to use the one in the @Daniel's answer.

From Python 2.7, you can also omit that positional argument and just use {}: -

print "Id: {}, Neighbour: {}".format(self.id, self.neighbours)

Upvotes: 2

Daniel Baktiar
Daniel Baktiar

Reputation: 1712

You can also use string formatting:

print('id: %s, neigbors: %s' % (self.id, str(self.neighbors)))

Upvotes: 2

Related Questions