Lia
Lia

Reputation: 5

I don't understand what causes this to happen in Python with class

class Song(object):
    def __init__(self, lyrics):
        self.lyrics = lyrics

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

cheese = "Happy birthday to you,\nI dont want to get sued,\nSo I'll stop right there"

bulls_on_parade = Song(["They rally around tha family",
                    "With pockets full of shells"])
Song([cheese]).sing_me_a_song()
bulls_on_parade.sing_me_a_song()

Here I'm talking about the Song([cheese]).sing_me_a_song() I made.

If I enter it as song(cheese).sing_me_a_song()

t
h
i
s
h
a
p
p
e
n
s

However if I put brackets like this song([cheese)].sing_me_a_song it is fixed. What causes this? Is the brackets related to a list

Upvotes: 0

Views: 51

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124758

Strings are iterable, just like lists are. You are passing in a single string, which can be iterated. However, when iterating over a string, you get each individual character, which is why you get your output:

>>> cheese = "Happy birthday to you,\nI dont want to get sued,\nSo I'll stop right there"
>>> for i in cheese[:5]:  # first 5 characters
...     print i
... 
H
a
p
p
y

If you expected there to be separate lines, then create a list with those lines:

cheese = ['Happy birthday to you,', 'I dont want to get sued,', "So I'll stop right there"]

or have Python create the list from the string using the str.splitlines() method:

>>> cheese = "Happy birthday to you,\nI dont want to get sued,\nSo I'll stop right there"
>>> cheese.splitlines()
['Happy birthday to you,', 'I dont want to get sued,', "So I'll stop right there"]

e.g. pass the latter to your song() class:

song(cheese.splitlines()).sing_me_a_song()

Upvotes: 3

Related Questions