The Wayback Machine - https://web.archive.org/web/20240711150449/https://www.geeksforgeeks.org/python-string-join-method/
Open In App

Python String join() Method

Last Updated : 01 Jul, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python join() is an inbuilt string function used to join elements of a sequence separated by a string separator. This function joins elements of a sequence and makes it a string.

Python String join() Syntax

Syntax: separator_string.join(iterable)

Parameters:

  • Iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set

Return Value: The join() method returns a string concatenated with the elements of iterable.

Type Error: If the iterable contains any non-string values, it raises a TypeError exception.

String join() in Python Example

In Python, we can use the join() method with different types of iterable such as Lists, Tuple, String, Dictionary, and Sets. Let’s understand them one by one with the help of examples.

Python
# This will join the characters of the string 'hello' with '-'
str = '-'.join('hello')
print(str)  # Output: h-e-l-l-o

Output:

h-e-l-l-o

Join a List into a String in Python

Here, we have joined the list of elements using the join() method in two ways firstly joined all the elements in the list using an empty string as a separator and also join the elements of the list using “$” as a separator as seen in the output.

Python
# Joining with empty separator
list1 = ['g', 'e', 'e', 'k', 's']
print("".join(list1))

# Joining with string
list1 = " geeks "
print("$".join(list1))

Output: 

geeks
$g$e$e$k$s$

Join a Tuple element into a String in Python

Here, we join the tuples of elements using the Python join() method in which we can put any character to join with a string.

Python
# elements in tuples
list1 = ('1', '2', '3', '4')

# put any character to join
s = "-"

# joins elements of list1 by '-'
# and stores in string s
s = s.join(list1)

# join use to join a list of
# strings to a separator s
print(s)

Output: 

1-2-3-4

Join Sets element into a String using join() method

In this example, we are using a Python set to join the string.

Note: Set contains only unique value therefore out of two 4 one 4 is printed.

Python
list1 = {'1', '2', '3', '4', '4'} 

# put any character to join
s = "-#-"

# joins elements of list1 by '-#-'
# and stores in string s
s = s.join(list1)

# join use to join a list of
# strings to a separator s
print(s)

Output: 

1-#-3-#-2-#-4

Joining String with a Dictionary using join()

When joining a string with a dictionary, it will join with the keys of a Python dictionary, not with values.

Python
dic = {'Geek': 1, 'For': 2, 'Geeks': 3}

# Joining special character with dictionary
string = '_'.join(dic)

print(string)

Output:

'Geek_For_Geeks'

Note: When we join the dictionary keys it only joins the keys which are string only not an integer let’s see this in the code.

Python
dic = {1:'Geek', 2:'For', 3:'Geeks'}

# Joining special character with dictionary
string = '_'.join(dic)

print(string)

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
string = '_'.join(dic)
TypeError: sequence item 0: expected string, int found

Joining a list of Strings with a Custom Separator using Join()

In this example, we have given a separator which is separating the words in the list and we are printing the final result.

Python
words = ["apple", "", "banana", "cherry", ""]
separator = "@ "
result = separator.join(word for word in words if word)
print(result) 

Output :

apple@ banana@ cherry

Python String Join() Method – FAQs

Can we use the join() method with a tuple of strings?

Yes, you can use the join() method with a tuple of strings. The join() method concatenates the elements of the tuple into a single string, using the specified separator.

Example:

tuple_of_strings = ('Hello', 'World')
result = ' '.join(tuple_of_strings)
print(result) # Output: "Hello World"

What happens if we use the join() method with non-string elements?

If you use the join() method with non-string elements, it will raise a TypeError because join() expects an iterable of strings. You need to convert non-string elements to strings first.

Example:

elements = [1, 2, 3]
# This will raise a TypeError
# result = '-'.join(elements)

# Convert elements to strings
result = '-'.join(map(str, elements))
print(result) # Output: "1-2-3"

How to join elements of a list with a space as a separator?

To join elements of a list with a space as a separator, use the join() method with a space character ' '.

Example:

list_of_strings = ['Hello', 'World']
result = ' '.join(list_of_strings)
print(result) # Output: "Hello World"

How to join elements of a list with a comma as a separator?

To join elements of a list with a comma as a separator, use the join() method with a comma character ','.

Example:

list_of_strings = ['apple', 'banana', 'cherry']
result = ','.join(list_of_strings)
print(result) # Output: "apple,banana,cherry"

Can the join() method be used with sets?

Yes, the join() method can be used with sets, but the elements must be strings. Note that sets are unordered, so the order of the elements in the resulting string may vary.

Example:

set_of_strings = {'apple', 'banana', 'cherry'}
result = ','.join(set_of_strings)
print(result) # Output: "banana,apple,cherry" (order may vary)


Previous Article
Next Article

Similar Reads

Python | Pandas str.join() to join string/list elements with passed delimiter
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of
2 min read
Python Pandas - Difference between INNER JOIN and LEFT SEMI JOIN
In this article, we see the difference between INNER JOIN and LEFT SEMI JOIN. Inner Join An inner join requires two data set columns to be the same to fetch the common row data values or data from the data table. In simple words, and returns a data frame or values with only those rows in the data frame that have common characteristics and behavior
3 min read
PySpark Join Types - Join Two DataFrames
In this article, we are going to see how to join two dataframes in Pyspark using Python. Join is used to combine two or more dataframes based on columns in the dataframe. Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,"type") where, dataframe1 is the first dataframedataframe2 is the second dataframecolumn_name i
13 min read
Outer join Spark dataframe with non-identical join column
In PySpark, data frames are one of the most important data structures used for data processing and manipulation. The outer join operation in PySpark data frames is an important operation to combine data from multiple sources. However, sometimes the join column in the two DataFrames may not be identical, which may result in missing values. In this a
4 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
Python | os.path.join() method
Os Path Module is a sub-module of the OS module in Python used for common pathname manipulation. In this article, we will learn about os.path.join() and handling file paths safely in Python OS. Python os.path.join() Method SyntaxSyntax: os.path.join(path, *paths) Parameter: path: A path-like object representing a file system path. *path: A path-lik
4 min read
numpy string operations | join() function
numpy.core.defchararray.join(sep, arr) is another function for doing string operations in numpy. For each element in arr, it returns a copy of the string in which the string elements of array have been joined by separator. Parameters: sep : It joins elements with the string between them. arr :Input array. Returns : Output array of str or unicode wi
1 min read
Python MySQL - Join
A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Python-MySQL-Connector This is a MySQL Connector that allows Python to access MySQL Driv
2 min read
Python SQLite - JOIN Clause
In this article, we discuss the JOIN clause in SQLite using the sqlite3 module in Python. But at first let's see a brief about join in SQLite. Join Clause A JOIN clause combines the records from two tables on the basis of common attributes. The different types of joins are as follows: INNER JOIN (OR JOIN) - Gives the records that have common attrib
5 min read
Python PostgreSQL - Join
In this article, we are going to see join methods in PostgreSQL using pyscopg2 in Python. Let's see the type of joins supported in PostgreSQL. Types of join:Inner joinFull join (outer join)Left joinRight joinCross join Tables for demonstration: Table 1: Employee table Table 2: Dept table The psycopg2.connect() method is used to connect to the datab
3 min read
Practice Tags :
three90RightbarBannerImg