Reputation: 329
I'm trying to create and play with classes in Python 3.6 but I'm getting the following error when I try to call a method that prints info about my class:
'TypeError: not enough arguments for format string'
And here's the code I'm trying to run:
class Restaurant(object):
def __init__(self, name, type):
self.name = name
self.type = type
def describe(self):
print("Restaurant name: %s , Cuisine type: %s" % self.name, self.type)
def open_restaurant(self):
print("%s is now open!" % self.name)
my_restaurant = Restaurant("Domino", "Pizza")
my_restaurant.describe()
my_restaurant.open_restaurant()
The open_restaurant() method works fine but with my_restaurant.describe() I receive the error message I mentioned.
Upvotes: 0
Views: 12479
Reputation: 912
This works (note the tuple to the right of "%")
print("Restaurant name: %s , Cuisine type: %s" % (self.name, self.type))
You might consider the newer form
print("Restaurant name: {} , Cuisine type: {}".format(self.name, self.type))
Upvotes: 2
Reputation: 249462
You need to pass a tuple:
print("Restaurant name: %s , Cuisine type: %s" % (self.name, self.type))
But really, the %
type of string formatting has been mostly obsolete in Python for many years, and you probably should not be using it in Python 3.6. Instead: try this:
print("Restaurant name: {} , Cuisine type: {}".format(self.name, self.type))
Or of course:
print("Restaurant name:", self.name, ", Cuisine type:", self.type)
Upvotes: 1
Reputation: 1579
Seeing as you are using python3.6. f-strings
are much nicer.
class Restaurant(object):
def __init__(self, name, type):
self.name = name
self.type = type
def describe(self):
print(f"Restaurant name: {self.name}, Cuisine type: {self.type}")
def open_restaurant(self):
print(f"{self.name} is now open!")
my_restaurant = Restaurant("Domino", "Pizza")
my_restaurant.describe()
my_restaurant.open_restaurant()
Restaurant name: Domino, Cuisine type: Pizza
Domino is now open!
Upvotes: 2