Bug? exec converts '\n' to newline in docstrings!?

Steve Holden steve at holdenweb.com
Mon Jul 30 11:51:35 EDT 2007


Edward K Ream wrote:
> It looks like both exec and execfile are converting "\n" to an actual 
> newline
> in docstrings!
> 
> Start idle:
> 
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on
> win32
> [rest of signon deleted]
> 
>>>> s = '''\
> strings = 'abc'.split("\n")
> '''
>>>> print s
> strings = 'abc'.split("
> ")
> 
> I see this in my own calls to exec and execfile.  Is this a bug or am I
> missing something?
> 
Python is doing exactly what you told it to do. You created a string 
with triple single-quote delimiters. Nothing in the string literal 
syntax says that escape sequences will not be actioned, so the literal 
has a value that includes a newline.

This has nothing to do with exec, and I don't believe it will happen 
with execfile should you create a file with a legal Python program 
inside it. The problem is because you are trying to represent a Python 
program as a Python string literal, and doing it incorrectly.

What you did is no different from writing:

 >>> s = '''\
... This is a string with\nan embedded newline'''
 >>> print s
This is a string with
an embedded newline
 >>>

It just doesn't match your expectations, is all.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list