6
\$\begingroup\$

Because I don't like using \ to break long lines (to comply with PEP8), I tend to do something like this:

message = "There are {} seconds in {} hours."
message = message.format(nhours*3600, nhours)
print(message)

It also makes code cleaner. Is this an okay way of doing things?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Not really a Code Review, I feel this is more appropriate at Programmers.SE. \$\endgroup\$ – Steven Jeuris Apr 7 '11 at 18:33
  • 4
    \$\begingroup\$ I think this is perfectly on-topic here. \$\endgroup\$ – Timwi Apr 8 '11 at 2:35
2
\$\begingroup\$

It's more than okay, it is nicely readable, has no problems and involves no abuse whatsoever. I sometimes do the same.

\$\endgroup\$
-2
\$\begingroup\$

Nothing necessarily wrong with doing that - I use that for situations that the message would be used more than once. However, for one-shot, multiline messages I'd do:

message =  "There are %d seconds " % nhours*3600
message += "in %d hours." % nhours
print message

Honestly, the only difference is stylistic. I prefer this method because it places the variables directly within the string, which I feel is more readable.

\$\endgroup\$
8
  • \$\begingroup\$ What does it places the variables directly within the string mean? \$\endgroup\$ – tshepang Apr 7 '11 at 17:33
  • \$\begingroup\$ Maybe a bad wording there. I mean that since the variable is assigned in the same line as the string, it's a bit clearer what goes where. In fact, I'd prefer msg = "There are " + nhours*3600 + " seconds in " + nhours + " hours." but I'm not certain whether you can do that in Python. \$\endgroup\$ – Michael K Apr 7 '11 at 17:40
  • \$\begingroup\$ That's a lot uglier I think, but yeah you can do that. You just need to convert your integers to string: msg = "There are " + str(nhours*3600) + " seconds in " + str(nhours) + " hours.". \$\endgroup\$ – tshepang Apr 7 '11 at 17:43
  • \$\begingroup\$ Like I said, matter of personal style :) \$\endgroup\$ – Michael K Apr 7 '11 at 18:01
  • \$\begingroup\$ You do lose reuseability which is important to note (without putting this code in a function). Ofcourse this isn't relevant if you only format once. \$\endgroup\$ – Steven Jeuris Apr 7 '11 at 18:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.