[Tutor] To FORMAT or not to
Chris Warrick
kwpolska at gmail.com
Sun Jan 3 08:04:22 EST 2016
On 3 January 2016 at 13:27, yehudak . <katye2007 at gmail.com> 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?
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
The programmer was not very intelligent in his use of str.format in
the first place. A more sensible way to write this is:
print("You've visited {0} & {1}.".format(island, new))
Formatting with constant strings is pointless, just include it in the
original input. However, string formatting is not.
Here are a couple of reasons:
* String formatting works everywhere, but this syntax is specific to
print() — if you use something else, you might end up producing faulty
code
* The corrected string formatting usage is more readable than the
original print()
* String concatenation with + requires that all arguments are strings,
which is even less readable
* With string formatting, you can apply special formatting to your
inputs (eg. set width, number precision…), which is hard or impossible
with print()
* Using print() with commas adds spaces between all entries, which
might look bad (and it does in this example); the only way to prevent
that is by setting `sep=`, but then you need to remember about a space
after "visited" and around the ampersand…
* Easy to localize (translate into different languages), which is
generally impossible with any of the other options (some languages
might rearrange the sentence!)
--
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
More information about the Tutor
mailing list