Python string join method; Through this tutorial, i am going to show you how to Join String in python with the space, comma and any delimiter.
How to join string in python
The Python built-in string join() function is the concatenation or join of the strings in iterable with string object as a delimiter.
Note:- The python join() function is built-in python function.
Syntax of Python String join() function is:
The iterable elements must be a string, otherwise
TypeError will be raised.
The separator between elements is the string providing this method.
Parameters of join() function
The join() method takes an iterable – objects capable of returning its members one at a time
Some of the example of iterables are:
- Native datatypes – List, Tuple, String, Dictionary and Set
- File objects and objects you define with an __iter__() or __getitem()__ method
Return Value from join()
The join() method returns a string concatenated with the elements of an iterable.
Example 1: Python string join with comma
Let’s look at some examples of string join() method.
s1 = ','.join(['a', 'b', 'c']) print(s1)
The string object can have multiple characters too.
s = 'abc' s1 = s.join('xyz') print(s1)
Notice that string is iterable. Here iterable elements are ‘x’, ‘y’ and ‘z’. They are concatenated together with ‘abc’ as the separator i.e. ‘x’+’abc’+’y’+’abc’+’z’.
Example 2: Python string join with space
Concatenate a sequence of strings (list, tuple) using join() function. The string object should be an empty string.
s1 = ' '.join(['a', 'b', 'c']) print(s1) s1 = ' '.join(('a', 'b', 'c')) print(s1)