1

I enforce strictly 80 characters per line in my python codes, but occasionally I have to break a line of string into two as following

print time.strftime("%m/%d/%Y %I:%M:%S \
    %p",time.localtime(os.path.getmtime(fname)))

in which case the output will have extra spaces in front of the "AM/PM", like

foo.dat was last modified: 01/10/2012 02:53:15                    AM

There are easy way to fix this, simply to either avoid cutting off strings, or allow long lines in this case, however, I am wondering if there are other more intrinsic ways to tackle this while allowing both str-cutting and line-breaking to happen. The second line is automatically indented by the editor, I don't want to change that either. Thanks.

nye17
  • 12,857
  • 11
  • 58
  • 68
  • 1
    possible duplicate of [Python style - line continuation with strings?](http://stackoverflow.com/questions/5437619/python-style-line-continuation-with-strings) – Wooble Jan 10 '12 at 15:07

2 Answers2

7

The recommended way to do this is to avoid using \ altogether by using parentheses instead. Also, use the fact that consecutive strings are concatenated into one string. For example:

print time.strftime(("%m/%d/%Y %I:%M:%S "
    "%p"), time.localtime(os.path.getmtime(fname)))
Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96
2

Yes.

>>> x = "one two three "\
... "four five six"
>>> x
'one two three four five six'

For clarity, in a Python source file:

x = "one two three "\
"four five six"

or

print time.strftime("%m/%d/%Y %I:%M:%S"\
" %p",time.localtime(os.path.getmtime(fname)))
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
Joe
  • 46,419
  • 33
  • 155
  • 245
  • apparently I cannot apply your answer to the example above where the string is actually for formatting, or am I missing something? – nye17 Jan 10 '12 at 15:01
  • Works for me. That was the Python interpreter shell (i.e. dots are produced by python shell). See my edit for what you'd put in a Python source file. – Joe Jan 10 '12 at 15:06