This seems like a question that should already have an answer, but I didn't find one. If anyone knows of another question that has already answered this, please post a comment with the link.
My question is, is there a way to input the items from a list into a string using the .format method? Using specific indices to format is kind of a pain, I am wondering if it is possible to use a "for i in list" technique.
So rather than this:
x = [1, 2, 3, 4, 5]
print 'The first 4 items in my list are {}, {}, {}, {}'.format([x[0], x[1], x[2], x[3])
I could do something like:
x = [1, 2, 3, 4, 5]
print 'The first 4 items in my list are {}, {}, {}, {}'.format([i for i in x if i < 5])
if I try something along these lines, it won't work and I will get a "tuple index out of range" error, because it sees this as only 1 item rather than 4 separate items. I'm just wondering if this is possible.
You can simply unpack the list:
>>> x = [1, 2, 3, 4, 5]
>>> 'The first 4 items in my list are {}, {}, {}, {}'.format(*x)
'The first 4 items in my list are 1, 2, 3, 4'
>>>
Any remaining arguments will be ignored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With