Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't split each element of string to a new lines

I have a problem to split each element of string into new lines using class.

I have to define my own class Songs and I have to use into this class _ _ init _ _ which should contain arguments: self, lyrics. Into that class I have to create method sing_me which is going to split every element of string (Songs) into new lines.

Output should look like:
When it"s black,
Take a little time to hold yourself,
Take a little time to feel around,
Before it"s gone!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have to contain this line in main function and the goal is to split every element of Songs to a new line.

Let_go = Songs(['When it"s black, ', 'Take a little time to hold yourself, ', 'Take a little time to feel around, ', 'Before it"s gone!'])

I tried many solutions to make it work but I have no idea how to solve that problem.

class Songs:
    def __init__(self, lyrics):
        self.lyrics = lyrics
    def sing_me(self):
        # Tried both solutions but any of them aren't working
        # print("\n".join(self.lyrics))
        # for line in self.lyrics: print(line)

def main():
    Let_go = Songs(['When it"s black, ', 'Take a little time to hold yourself, ', 'Take a little time to feel around, ', 'Before it"s gone!'])  
    # Here are my tries:
    # Let_go.sing_me()
    # Let_go = Songs.sing_me((['When it"s black, ', 'Take a little time to hold yourself, ', 'Take a little time to feel around, ', 'Before it"s gone!']))

>Solution :

I just ran your original code with the for loop and it worked like you asked:

class Songs:
    def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me(self):
        for line in self.lyrics:
            print(line)


if __name__ == '__main__':
    Let_go = Songs(['When it"s black, ', 'Take a little time to hold yourself, ',
                    'Take a little time to feel around, ', 'Before it"s gone!'])
        # Here are my tries:
        # Let_go.sing_me()
        # Let_go = Songs.sing_me((['When it"s black, ', 'Take a little time to hold yourself, ', 'Take a little time to feel around, ', 'Before it"s gone!']))
    Let_go.sing_me()

output:

When it"s black, 
Take a little time to hold yourself, 
Take a little time to feel around,
Before it"s gone!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading