[Tutor] To FORMAT or not to

yehudak . katye2007 at gmail.com
Sun Jan 3 09:40:05 EST 2016


Important point. Thanks again.
Yehuda

On Sun, Jan 3, 2016 at 3:10 PM, Francois Dion <francois.dion at gmail.com>
wrote:

> And as Chris points out, if there is any possibility that the words will
> be in a different order in a different language, use {0}, {1} instead of {}.
>
>
> Francois
>
> On Sun, Jan 3, 2016 at 8:04 AM, Chris Warrick <kwpolska at gmail.com> wrote:
>
>> 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
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> raspberry-python.blogspot.com - www.pyptug.org - www.3DFutureTech.info -
> @f_dion
>


More information about the Tutor mailing list