Python Join is a Sting function (method) and it returns a string, where the elements of the sequence have been joined by a string separator. So you to choose a separate as stings like comma, hash, space or other separators.
The best way to describe it is when you have two separate strings and want to merge them so that they become one.
Don’t confuse with adding (Concatenation) a sting like str = ‘hello’ + ‘world’, Here is using a string as a glue to add sequence like list, tuple, string etc.
Syntax:
string_name.join(iterable/sequence)
Parameters
Iterable (sequence) – Any iterable object (elements) were all the returned values are strings.
Some data types are List, Tuple, String, Dictionary, and Set.
Return Value
Python join() function returns a string concatenated (link together in a chain or series) with the elements of iterable. The separator between elements is the string providing this method.
Python join() function examples
Here you will lean example of join() function in python with different data types.
Comma separator
Join all items in a tuple into a string, using a comma as separator, you can use another separator.
str = ","; tup = ("a", "b", "c") print(str.join(tup))
Output : a,b,c
Join all items of List into String.
str = ","; list1 = ['EyeHunt', 'Tutorial','Python'] print(str.join(list1))
Output: EyeHunt, Tutorial, python
Join all items in Strings.
str = ","; str1 = "Python" print(str.join(str1))
Output : P,y,t,h,o,n
Without separator (empty string)
Join all items in a tuple into a string, using a none separator:
str = '' seq = ("a", "b", "c") print(str.join(seq)) #or print(''.join(seq))
Output: abc
abc
This is a basic example of join() Function with some data type, you can do with other data like sets, dictionaries, etc. Also, do practice with different parameters.
QA: Interview Questions
# What if you tired a join a string used int sequences, like this
str = ","; list1 = (1, 'Eye', 'Hunt') print(str.join(list1))
Answer: It will throw an error –TypeError: sequence item 0: expected str instance, int found
# Why is it string.join(list) instead of list.join(string)?
Answer: Because any iterable can be joined, not just lists, but the result and the “joiner” are always strings.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All Python Join Function is in Python 3, so it may change its different from python 2 or upgraded versions.