What is .format?

I have got to the activity on the repr method in classes

Frequently in the answers .format is used with some kind of curly bracket thing but I can’t find anywhere in the course which explains what this is or why it is used or what it means.

As in here:

class Circle:
pi = 3.14

def init(self, diameter):
self.radius = diameter / 2

def area(self):
return self.pi * self.radius ** 2

def circumference(self):
return self.pi * 2 * self.radius

def repr(self):
return "Circle with radius {radius}".format(radius=self.radius)

medium_pizza = Circle(12)
teaching_table = Circle(36)
round_room = Circle(11460)


Please can someone explain this in a very simple way.

It’s a method to include ‘variables’ inside a string object. To do so any objects which aren’t already strings would need to be converted into a string format and this isn’t always simple (e.g. how many decimal points should a float have) and you may want different formatting at different times. The .formatmethod is designed for this purpose. The docs have details on the .format method-

For a simpler explanation and couple of examples I quite like the following page but there are many other examples and pages dedicated to explaining it-

1 Like

As an extra note, as of python 3.6, they have made the process of including variables in a string even easier with the use of f-strings.

Instead of:

n = 6
string = "You have {number} bananas!".format(number=n)

You can now simply do:

n = 6
string = f"You have {n} bananas!"
1 Like

Thank you so much for your help.

I understand what you’ve written in the first paragraph (although I really struggle to understand either of the pages you’ve mentioned :disappointed_relieved:).

But I don’t really understand the syntax.

This was an earlier example of the same thing:


class Circle:
pi = 3.14

Add constructor here:

def init(self, diameter):
print(“New circle with diameter: {diameter}”.format(diameter=diameter))

teaching_table = Circle(36)

Why is the word diameter needed 4x?? As a beginner this feels insane and overly complex.

I understand that the first time, Diameter is the word you want printed in the string, and in the curly brackets ((from what you said above) - you are telling the computer to change the number of the diameter to a piece of string). But why do you need to include diameter again twice in the .format brackets?

In the .format() method you are unable to put a variable directly into the string, as such .format has to assign each curly bracket variable a value from the scope outside of the string.

As goes the first diameter within .format() is referring to the word inside of curly brackets, the second diameter is assigning that word a value from within your program. As such, the word with in the curly braces could be changed to anything as long as you change it inside of the .format():

#     A local variable diameter is created equal to 5
#    /
diameter = 5
string = "New circle with {n}".format(n=diameter)
#                         /            \    \
#   n currently has no value            \    and this sets n as equal 
#                                        \   to diameter, or 5
#                                         This selects n from the string
1 Like

I think that one is overcomplicated to be honest. You could reduce the number of uses, for example-

print("New circle with diameter: {}".format(diameter))

The placeholders can be used in situations where multiple values are passed and they aren’t necessarily in order.

egg = 2
bigegg = 4
print('my egg has a diameter of {} and my bigegg has a diameter of {}'.format(egg, bigegg))
Out: my egg has a diameter of 2 and my bigegg has a diameter of 4

# By using numbers we can swap the order and also use repeats
print('my bigegg has a diameter of {1} and my egg has a diameter of {0}\nWith a diameter of {1} my bigegg is bigger.'.format(egg, bigegg))
Out: my bigegg has a diameter of 4 and my egg has a diameter of 2
With a diameter of 4 my bigegg is bigger.

With multiple values even numbers rapidly become very confusing. That’s when using names in the style of '{name}'.format(name=myvariable) becomes useful.

As per the suggestion of @8-bit-gaming an f-string would simplify this example greatly if you’re working with python3.
Both these expressions have the same output:

print(f"New circle with diameter: {diameter}")
print("New circle with diameter: {diameter}".format(diameter=diameter))
Out: New circle with diameter: 3.0

Or my favourite in recent versions of Python (not sure if it was backported so you may have to test)-

print(f"New circle with {diameter = }")
Out: New circle with diameter = 3.0

Now we’re down to a single term but it may require 3.7 or so.

1 Like

Ok that’s clearer thank you.

I think one of the hardest things in python is how everything has a similar name especially when you have things like:

for player,words in player_to_words.items():
player_points = 0
for word in words:
player_to_points += score_word(word)
player_to_points[player] = player_points

Just looking at the code with the word(s) and player(s) repeated so many times is confusing to a beginner. I think it’s because I come from a background of learning foreign languages rather than code. I just want things to be clear and easily differentiated.

1 Like

You don’t have to name them like that. I think CC teaches it like that because it thinks that is what people find the easiest, but you could call the variable player anything you wanted; you can name it whatever is easiest for you (just as long as it is the same thoughout all the code).