7

Let's say I have a list datalist, with len(datalist) = 4. Let's say I want each of the elements in the list to be represented in a string in this way:

s = "'{0}'::'{1}'::'{2}' '{3}'\n".format(datalist[0], datalist[1], datalist[2], datalist[3])

I don't like having to type datalist[index] so many times, and feel like there should be a more effective way. I tried:

s = "'{0}'::'{1}'::'{2}' '{3}'\n".format(datalist[i] for i in range(4))

But this doesn't work:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

Does anybody know a functioning way to achieve this efficiently and concisely?

2 Answers 2

6

Yes, use argument unpacking with the "splat" operator *:

>>> s = "'{0}'::'{1}'::'{2}' '{3}'\n"
>>> datalist = ['foo','bar','baz','fizz']
>>> s.format(*datalist)
"'foo'::'bar'::'baz' 'fizz'\n"
>>>

Edit

As pointed out by @AChampion you can also just use indexing inside the format string itself:

>>> "'{0[0]}'::'{0[1]}'::'{0[2]}' '{0[3]}'\n".format(datalist)
"'foo'::'bar'::'baz' 'fizz'\n"
Sign up to request clarification or add additional context in comments.

5 Comments

@Sandi yes, I've linked to the relevant documentation.
You can also just index in the format string "'{0[0]}'::'{0[1]}'::'{0[2]}' '{0[3]}'\n".format(datalist)
@Sandi read through the answers to this question
Fot this method to work I'd have to know how many items the list has. What if I don't know beforehand how many items are in the list?
@kronosjt it depends on exactly what you are trying to accomplish. What sort of string are you trying to construct?
0

List comprehension with enumerate() may be what you are looking for. You would not need to reference a list length with enumerate.

_>>enumerate(datalist) will return a tuple numbering the list items starting with default 0.

datalist = ['foo','bar','baz','fizz']    
[print('{}::{} '.format(index,data),end='') for index,data in enumerate(datalist)]
print()  #start new line

Output:

0::foo 1::bar 2::baz 3::fizz 

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.