3

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.

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use string.join() on your list comprehension

x = [1, 2, 3, 4, 5]

print 'The first 4 items in my list are {}'.format(', '.join([str(i) for i in x if i < 4]))
# The first 4 items in my list are 1, 2, 3

Note: This only prints three elements, since only 3 elements in x match < 4

If your list comprehension was just an attempt to output only 4 elements, and you're not really interested in using list comprehensions otherwise, iCodez's solution is better and more efficient.

Comments

0
rev_arr = [4,3,2,1]
str_arr.format(', '.join([str(element) for element in rev_arr]))

I want that it should give an ouput like this 4 3 2 1 but its returning an empty string . I am not able to understand why its returning an empty string. I am newbie please elaborate the second line of the snippet to me

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.