[Tutor] To FORMAT or not to

Peter Otten __peter__ at web.de
Sun Jan 3 08:09:24 EST 2016


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?

I don't see the benefits either. If anything I'd move the constants into the 
format string:

print("You've visited {island}, & {new}.".format(island=island, new=new))

If you use the same names in your format string and your code it should 
suffice to read the format string to get an idea of what will be printed.

In future versions of Python you can simplify it to

print(f"You've visited {island}, & {new}.")

https://www.python.org/dev/peps/pep-0498/



More information about the Tutor mailing list