Reputation: 5206
In python to print a formatted string with ints and strings, I'd usually do :
print '%d %d - %s' %(x,y, mystr)
Is there anything similar for printing out a list? I have:
L= [1,0,0]
name = 'V'
and I want the output to be :
v(1,0,0)
Is there anything similar to %d for list objects?
Upvotes: 3
Views: 5956
Reputation: 52738
You can always subclass list
, then overwrite the repr
function to print the list
in whatever format you want, like so:
In [1]: class MyList(list):
def repr(self):
return ", ".join(["%s" % s for s in self])
In [2]: x = MyList([1, 2, 3, 4, 5])
In [3]: x
Out[3]: [1, 2, 3, 4, 5]
In [4]: print x
[1, 2, 3, 4, 5]
In [5]: print "abc__ %s __def" % x
abc__ [1, 2, 3, 4, 5] __def
In [6]: y = MyList()
In [7]: y.append(55)
In [8]: y.append("abc")
In [9]: y
Out[9]: [55, 'abc']
In [10]: print "ZZZ -- %s -- ZZZ" % y
ZZZ -- [55, 'abc'] -- ZZZ
Upvotes: 1
Reputation: 39950
If you want complete control how the list gets rendered, you'll have to format it separately.
In your case, the code would be something like:
items = [1,0,0]
name = 'V'
formatted = '%s(%s)' % (
name,
','.join(str(it) for it in items)
)
Upvotes: 8