0

I'm working on a project right now and as one of the features, I'm supposed to traverse through a list and output the items in different lines.

The code looks something like this:

dictionary = {'key0': sorted([item + "\n" 
              for item in mylist}])

print(x[1]) for x in dictionary.items()

However, this leaves a trailing newline every time.

Would something like this work?

string = ''

otherlist = sorted([item + "\n" for item in mylist])

for i in range(len(otherlist)):
    string.join(sorted[i])

string.rstrip()

print(string)

Are there any better ways to do this?

magikarp
  • 460
  • 1
  • 8
  • 22

2 Answers2

0

Use str.join:

print("".join(x[1] for x in dictionary.items()))
Netwave
  • 40,134
  • 6
  • 50
  • 93
0

Instead of adding the newline in your list comprehension, simply join the list with newlines.

lines = '\n'.join(otherlist)
Soviut
  • 88,194
  • 49
  • 192
  • 260