Python Forum

Full Version: New to Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey all, hope everyone is doing great.  New python coder here.  My question is, what's the difference between the two codes below? When I run it, there doesn't seem to be any difference.  Both codes run. Can someone explain why formatting is needed?  Thanks in advance.

print ("Its fleece was white as {}.".format(snow))
and print ("Its fleece was white as snow")?
Hi OptimusBri,

As it looks like you have gathered, both lines of code produce similar output.

The difference comes down to the fact that the line "formats" the word "snow" and it wil insert this formatted text between the "{}".

There are a number of reasons for fomatting text, the main two are:
1) To convert the data type of the variable. This can be to change from a numeric variable to a string variable. The reason for this can be to ensure that the variable can be accessed by string manipulation commands.
2) The second is to display the variable in a certain way or "format" e.g. width or alignment. You may wish to have you string variables ("text") display left justified and you numeric variables displayed right justified. Having numbers left justifies can cause problems:
1
100
1000
------
Trying to add these together would give you a "result" of 3000 when the actual result is 1101.
This can also cause issues when sorting the data as, in the above example, the values will all appear as the same. A little artistic license is taken with these examples, but hopefully will give you an idea.

The format "command" is a part of the Python system as opposed to a function developed to enhance the existing system. Further details of this format function can be seen at this link. Some of these options are "similar" to the concept of formatting cells in Excel.

https://docs.python.org/3.4/library/func...ml?#format

Hope this gives you some help to answering you question.

Good Luck

Bass
Really?  When I run:

print ("Its fleece was white as {}.".format(snow))
I get:

Error:
Traceback (most recent call last):  File "<stdin>", line 1, in <module> NameError: name 'snow' is not defined
In your first example, the '{}' acts as a place holder for the elements in the '.format()' segment, in this case it is looking for the variable named snow.

snow = "snow"
print("It's fleece was white as {}".format(snow))
Output:
Its fleece was white as snow.
In your second example you are simply printing the string "Its fleece was white as snow."

Please see String Formatting
Thank you both! I will have to read the link that Bass gave. I recently got this book "Learn Python 3 the hard way" and it said to ask a more seasoned programmer. Again thanks for the reply.