Python Join Function | Join Strings

Python Join is a Sting function (method) and it returns a string, where the elements of the sequence have been joined by 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.

Python Join Function | Join String, Tuple, List, Set

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:

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.

Output : a,b,c

Join all items of List into String.

Output: EyeHunt, Tutorial, python

Join all items in Strings.

Output : P,y,t,h,o,n

Without separator (empty string)

Join all items in a tuple into a string, using a none separator:

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

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.6

Python 3.7

All Python Join Function are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.