简体   繁体   中英

list printing in formatted string in python

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM