0

Class A contains a list of type class B, which contains a print function. I am trying to return a String of all of the printed elements in B, separated by a new line. What is the Pythonic 'single-line' way for method GetList()?

class A():
    # .....
    def GetList(self):
        temp = ""
        for item in self.ListOfTypeClassB:
            temp += item.Print() + "\n"
        return temp

I can add the newline to the print method if that makes it cleaner.

Kevin
  • 74,910
  • 12
  • 133
  • 166
  • This doesn't have anything to do with classes really. You are concatenating a series of strings, it doesn't matter where those came from. – Martijn Pieters Dec 22 '15 at 18:13
  • `return '\n'.join([item.Print() for item in self.ListOfTypeClassB]) + '\n'`. – Martijn Pieters Dec 22 '15 at 18:14
  • That is true, I did not know if adding the additional information would help. I can remove all of the related class information if you think that makes the question more specific. – Python N00b Dec 22 '15 at 18:16
  • I've already linked you to a duplicate; use `str.join()`, and the method calls can be done in a list comprehension passed to that method. – Martijn Pieters Dec 22 '15 at 18:16
  • Thank you Martijn (and Kevin) for the super fast answers. I actually had looked at that thread but over-thought it because I was making class calls. This website is a lifesaver. – Python N00b Dec 22 '15 at 18:22

0 Answers0