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?

doobeedoobee
  • 406
  • 6
  • 19

2 Answers2

0

Use str.join:

print("".join(x[1] for x in dictionary.items()))
Netwave
  • 36,219
  • 6
  • 36
  • 71
0

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

lines = '\n'.join(otherlist)
Soviut
  • 83,904
  • 44
  • 175
  • 239