[Tutor] String Replace..... [octal numbers]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 28 Jan 2001 15:55:04 -0800 (PST)


On Sun, 28 Jan 2001, Budgester wrote:

> I'm new to Python as well, the reason I was using \012 was because
> that's what was returned when i did a debugging print statement,

Hmmm... let me go off on a tangent on '\012', and then go back to the
original question.

It turns out that Python thinks that '\012' and '\n' are the same thing:

###
>>> '\n' == '\012'
1
###

What's neat is that characters can be thought of as numbers.  We can see
this more clearly by using the ord() "ordinal" and chr() "character"
functions, which let us explore this more:

###
>>> ord('\n')
10
>>> chr(ord('\n'))
'\012'
###

But at first, this is weird!  Why is the ordinal value of '\012' equal to
10?  Apparently, it's reversable, since we can go from a character back to
its ordinal number back to its character, but where did that 10 come from?

One way we can get 10 out of '\012' is like this:

    10 =   1 * 8**1
         + 2 * 8**0

That is, it has to do with "octal" numbers, that is, numbers that are
represented in terms of powers of 8's.  Python shows us the special
characters (newlines, tabs, etc.) in octal.  To tell the truth, I'm not
quite sure why, but there's probably a good reason for it.  *grin*

Likewise, if we try something like this:

###
>>> num = 0223
>>> num
147
###

We can see that:

    147 = 2 * 8**2
        + 2 * 8**1
        + 3 * 8**0

It's weird, but it's neat to see a glimpse of something a little foreign
at times.




Anyway, to go back to your original problem, the error that pops up:

###
 File "c:\python20\lib\string.py", line 363, in replace
    return s.replace(old, new, maxsplit)
###

is really wacky, since that's part of the standard library.  I think that
another part of your code might have accidently touched string's version
of replace(), so let's take a look at the full code.