- How does string join work in Python?
- Why is join() a string method instead of a list or tuple method?
- ================================================================
- Strings became much more like other standard types starting in Python
- 1.6, when methods were added which give the same functionality that
- has always been available using the functions of the string module.
- Most of these new methods have been widely accepted, but the one which
- appears to make some programmers feel uncomfortable is:
- ", ".join(['1', '2', '4', '8', '16'])
- which gives the result:
- "1, 2, 4, 8, 16"
- There are two common arguments against this usage.
- The first runs along the lines of: "It looks really ugly using a
- method of a string literal (string constant)", to which the answer is
- that it might, but a string literal is just a fixed value. If the
- methods are to be allowed on names bound to strings there is no
- logical reason to make them unavailable on literals.
- The second objection is typically cast as: "I am really telling a
- sequence to join its members together with a string constant". Sadly,
- you aren't. For some reason there seems to be much less difficulty
- with having "split()" as a string method, since in that case it is
- easy to see that
- "1, 2, 4, 8, 16".split(", ")
- is an instruction to a string literal to return the substrings
- delimited by the given separator (or, by default, arbitrary runs of
- white space).
- "join()" is a string method because in using it you are telling the
- separator string to iterate over a sequence of strings and insert
- itself between adjacent elements. This method can be used with any
- argument which obeys the rules for sequence objects, including any new
- classes you might define yourself. Similar methods exist for bytes and
- bytearray objects.
- Python - The split() and join() methods - String Tutorial with Example
- Combining List Elements with join Method
- [inline]
Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.
Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license