Reputation: 3
I'm trying to write a function that can take a list and turn it into a string where each value is line seperated.
I've tried using string multiplication with formatting
d = ["one", "two", "three"]
dstring = ("{}\n"*(len(d)-1)).format(d)
print(dstring)
My intended result is that a set of braces would be generated per element in the list and could then be formatted with just the list.
So it would return
one
two
three
and any other elements in that format should the list get bigger.
But instead it returns
IndexError: tuple index out of range
Upvotes: 0
Views: 50
Reputation: 42748
format
needs n parameters, e.g. by using *
:
dstring = ("{}\n"*len(d)).format(*d)
Upvotes: 0
Reputation: 20490
Use str.join, which joins items in a list together, with the provided delimiter between them, which in our case is\n
d = ["one", "two", "three"]
res = '\n'.join(d)
print(res)
#one\ntwo\nthree
The output is
one
two
three
Or if you want the list with \n
appended at the end of each list, you can use a list-comprehension
d = ["one", "two", "three"]
res = [f'{item}\n' for item in d]
print(res)
The output is
['one\n', 'two\n', 'three\n']
Upvotes: 1
Reputation: 526
I would use a short list comprehension for this:
d = ["one", "two", "three"]
c = [b+"\n" for b in d]
print(c)
Which gives you the desired output:
['one\n', 'two\n', 'three\n']
Upvotes: 0