What exactly does the .join() method do?

后端 未结 9 2427
一向
一向 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:54

    To append a string, just concatenate it with the + sign.

    E.g.

    >>> a = "Hello, "
    >>> b = "world"
    >>> str = a + b
    >>> print str
    Hello, world
    

    join connects strings together with a separator. The separator is what you place right before the join. E.g.

    >>> "-".join([a,b])
    'Hello, -world'
    

    Join takes a list of strings as a parameter.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 10:59

    "".join may be used to copy the string in a list to a variable

    >>> myList = list("Hello World")
    >>> myString = "".join(myList)
    >>> print(myList)
    ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
    >>> print(myString)
    Hello World
    
    0 讨论(0)
  • 2020-11-22 11:08

    Look carefully at your output:

    5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
    ^                 ^                 ^
    

    I've highlighted the "5", "9", "5" of your original string. The Python join() method is a string method, and takes a list of things to join with the string. A simpler example might help explain:

    >>> ",".join(["a", "b", "c"])
    'a,b,c'
    

    The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].

    It appears that you're looking for + instead:

    print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring() + strid
    
    0 讨论(0)
  • 2020-11-22 11:10

    join() is for concatenating all list elements. For concatenating just two strings "+" would make more sense:

    strid = repr(595)
    print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
        .tostring() + strid
    
    0 讨论(0)
  • 2020-11-22 11:10

    There is a good explanation of why it is costly to use + for concatenating a large number of strings here

    Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.

    ''.join([a, b, c]) trick is a performance optimization.

    0 讨论(0)
提交回复
热议问题