.replace("a" or "b")

Cameron Simpson cs at cskk.id.au
Tue Jul 3 01:10:36 EDT 2018


On 03Jul2018 07:52, Abdur-Rahmaan Janhangeer <arj.python at gmail.com> wrote:
>that's another oddity i wanted to clear
>
>how do i know that string methods accept or and and in like .replace("a" or
>"b")
>
>i can't figure out how to deduce that it can accept that

Well, it accepts an expression like that, but it doesn't do what I think you 
think it does.

Here's the help on str's replace method:

    >>> help(str.replace)
    Help on method_descriptor:

    replace(...)
        S.replace(old, new[, count]) -> str

        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.

So you're supplying a value for the "old" parameter. And what you're supplying 
is the _result_ of the expression:

  "a" or "b"

So "replace" doesn't see a compound thing meaning 'replace "a" or replace "b"', 
it sees a single value. The "or" operator is a short circuiting operator, 
returning the first operand if it is true, otherwise the second.

Since "a" is considered true ("" is false, all the nonempty strings are true), 
the result of:

  "a" or "b"

is just "a". So replace() gets handed "a", and replaces instances of the string 
"a". The "b" never enters the picture.

So there's no gap in the documentation for replace: it accepts an old string 
and a new string. When you write:

  "a" or "b"

you're computing that value to pass to replace _before_ replace gets called.

I hope this clarifies what's going on.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list