Python String join() Method
The join() function is a Python built-in function used to join elements of a sequence. It returns a new string. It can be used with many data types List , Tuple , String , etc.
The way it is formulated is like this
string_name .join (iterable)
Argument (parameter) Iterable are objects that are able to return their elements one by one. Such as List, Tuple, String, Dictionary, and Set
Example:
# Joining with empty separator
list = ['a', 'h', 'm', 'e', 'd']
print("".join(list))
The output will be:
ahmed
In the previous example, we use the join() function to join the elements of a list. with an empty string " " . and returns a new string
You can replace the empty string with any character or symbol
Example :
list = {'1', '2', '3', '4', '5','6','6'}
# put any characher to join
string = "_"
# joins elements of list by '_'
# and stores in string a
a = string.join(list)
# join use to join a list of
# strings to a separator a
print(a)
The output will be:
3_4_2_5_1_6
Note: The array must contain unique values only so the repeating number 6 is not printed. Note also that the collection produces different outputs each time
Example:
# Joining with string
dic = {'Java': 1, 'C #': 2, 'Python': 3}
print(">".join(dic))
The output will be:
Java>C #>Python
In the previous example, we use the join() function to join the elements of a Dictionary. with a string containing a special character “<”. and returns a new string
External sources:
Built-in functions - official Python documentation
If you have any questions or concerns, leave them in the comments
Tags
Python String string methods python python string join method
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment