Python string join; In this tutorial, you will learn how to join two or more (multiple string) string in Python with space by using space, comma and any delimiter.
The join() method providesĀ a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string. The syntax of the join() method is: string.join(iterable)
To join the string, you can use the python join() function of Python. Here you will first learn about the python join function of join python such as the syntax of the join function, parameters, return value, etc. After this you will learn how to join a string in Python.
How to join string in python
The Python built-in stringĀ join() function is the concatenation 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:
str_object.join(iterable)
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)
Output:Ā
a,b,c
The string object can have multiple characters too.
s = 'abc'
s1 = s.join('xyz')
print(s1)
Output:Ā
xabcyabcz
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
We can 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)
Output:
abc abc
Recommended Python Tutorials