[Tutor] To FORMAT or not to

Mark Lawrence breamoreboy at yahoo.co.uk
Mon Jan 4 14:50:59 EST 2016


On 03/01/2016 13:12, Alan Gauld wrote:
> On 03/01/16 12:27, yehudak . wrote:
>> Hi there,
>> In a program I wrote the following line (Python 3.5):
>>
>> print("You've visited", island, '&', new + ".")
>>
>> A programmer told me that it's a bad habit, and I should have used instead:
>>
>> print("You've visited {0} {1} {2}{3}".format(island, "&", new, "."))
>>
>> May I understand why?
>
> There are several reasons although your technique is far from
> the worst way of doing things. And the format string here would probably
> be better written as:
>
> print("You've visited {0} & {2}.".format(island, new))
>
> ie only put the variables as placeholders.
>
> Why is it better?
> 1) It is slightly more performant. String addition and
> concatenation are relatively slow processes in Python.
> Formatting will usually be slightly faster. This is not
> a good reason in itself (and in your case with a single
> print it's probably irrelevant) but it's one factor. It
> does matter more if you are printing inside a loop with
> many variables and long strings. (For example assembling
> a web page). So it's a good habit to adopt.
>
> 2) It improves consistency. You can store the format
> string as a variable and then print it out many times
> from different parts of your code and it will always
> be the same. This makes it much easier to maintain
> your program. For example:
>
>      fmtString = "You've visited {0} & {2}."
>      if foo:
>        print(fmtString.format(foo,bar))
>      else:
>        print(fmtString.format(baz,bad))
>
> Now if you want to change the message you only need to
> change the text in one place rather than searching your
> code to do an edit. Also the user sees exactly the same
> formatting, no extra spaces in one message compared
> to another for example.
>
> 3) formatting provides many extra features to control
> justification, leading and spacing. This is especially
> important for numeric output where you can define the
> number of decimal places, whether a leading sign is
> included, padding with zeros etc, etc. You may not
> need that initially but if you do have to add it in,
> it's trivial with a format string but much more work
> if you have lots of hard coded messages all over your
> code.
>
> There may be other reasons too but that should give
> you some ideas.
>
>

Three reasons for why it's better but it doesn't actually work as given.

 >>> island = "Isle Of Wight"
 >>> new = "Isle of Wong"
 >>> print("You've visited {0} & {2}.".format(island, new))
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list