line continuations with backslash

Tim Peters tim.one at home.com
Fri Aug 24 23:23:29 EDT 2001


[Paul Rubin]
> Is there a particular reason in Python why you can't continue a line with
> a backslash in the middle of a literal, like in C?

Beats me; AFAIK it's the first time it's ever been asked, and the decision
is too old to channel the spirit of a much younger Guido.

> For what I'm doing it would be useful to be able to split a numeric
> literal like this:
>
> a = 123\
> 456\
> 789L
>
> The actual numbers I want to use are a few hundred digits, so
> splitting them across several lines would be nice.
>
> Is there another way to do this?  I guess I could enter
>
> a = long("123"+
>   "456"+
>   "789")

You don't need the "+" signs there; as in C, adjacent string literals are
catenated at compile-time.

I'd probably do something like

def s2long(s):
    return long(''.join(s.split()))

x = s2long("""
    123
    456
    789""")

-- or learn how to use the horizontal scroll bar in my editor <wink>.

> but that does an extra runtime conversation instead of just
> compiling the literal into the .pyc file.

Yup, and the way I'd do it costs even more, but I can't picture myself doing
this outside one-shot module initialization code, so wouldn't care how long
it takes.

god-forbid-michael-tells-you-about-bytecodehacks-ly y'rs  - tim





More information about the Python-list mailing list