String printing behavior?
tim_one at email.msn.com
Thu Mar 2 06:50:28 CET 2000
[posted & mailed]
> I've got a question about the string printing behavior. If I define a
> functions as:
> >>> def foo():
> ... return "line1\nline2"
> >>> foo()
> >>> print foo()
> It seems to me that the default printing behavior for strings should match
> behavior of the print routine. I realize that some people may want to
> see embedded control codes, but I would advocate a seperate method for
> printing raw byte sequences.
This isn't as mysterious as it appears. There are two builtin Python
functions that convert objects to strings: str(), and repr(). Whenever a
raw expression is entered at the interpreter prompt, if the resulting object
is not None then repr(object) is displayed. Similarly, every item given to
"print" is magically passed thru str() first. It's repr that converts
control characters to escape sequences in strings, while str(a_string)
simply returns a_string unaltered.
That explains what you're seeing, but now how to change it. Here's how you
change it: sit back and wait <wink>. There was quite a discussion about
this a while back, and it likely that a future release of Python will behave
more as you expect here, and/or even supply a new hook (via the sys module)
letting you specify whatever function *you* want applied to convert
expression-result objects to strings.
Until then, AFAIK there's no pleasant way for you to alter this behavior,
short of changing the implementation of the interpreter yourself.
relief-may-be-on-the-way-ly y'rs - tim
More information about the Python-list