What exactly does the .join() method do?

后端 未结 9 2584
一向
一向 2020-11-22 10:54

I\'m pretty new to Python and am completely confused by .join() which I have read is the preferred method for concatenating strings.

I tried:

         


        
9条回答
  •  借酒劲吻你
    2020-11-22 10:59

    join takes an iterable thing as an argument. Usually it's a list. The problem in your case is that a string is itself iterable, giving out each character in turn. Your code breaks down to this:

    "wlfgALGbXOahekxSs".join("595")
    

    which acts the same as this:

    "wlfgALGbXOahekxSs".join(["5", "9", "5"])
    

    and so produces your string:

    "5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5"
    

    Strings as iterables is one of the most confusing beginning issues with Python.

提交回复
热议问题