Aman Seth
Aman Seth

Reputation: 129

Not able to print the desired output in python

class Person:
    def __init__(self,name,age): #contructor method
        self.name = name
        self.age = age 
        print '(0) has been born'.format(self.name) 
p1 = Person("sam", 23)
p2 = Person("sunny", 22)

Im getting output:-
(0) has been born
(0) has been born
Expected output:-
sam has been born
sunny has been born

I am trying here to learn about the special methods starting with the init method. But I am not getting the desired output. Any help? Thanks

Upvotes: 2

Views: 56

Answers (3)

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

Use {} Check this LIVE IDEONE

Python

class Person:
    def __init__(self,name,age): #contructor method
        self.name = name
        self.age = age 
        print '{0} has been born'.format(self.name) 
p1 = Person("sam", 23)
p2 = Person("sunny", 22)

stdout

sam has been born
sunny has been born

Upvotes: 0

user3589561
user3589561

Reputation: 31

This works for me;

class Person:
    def __init__(self,name,age): #contructor method
        self.name = name
        self.age = age 
        print self.name+' has been born'
p1 = Person("sam", 23)
p2 = Person("sunny", 22)

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You have to use curly brackets {}:

print '{0} has been born'.format(self.name)

Note: You can see this link from Python Docs for more examples.

Upvotes: 6

Related Questions