Open In App

Python String join() Method

Last Updated : 28 May, 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


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 program to split and join a string
Python program to Split a string based on a delimiter and join the string using another delimiter. Splitting a string can be quite useful sometimes, especially when you need only certain parts of strings. A simple yet effective example is splitting the First-name and Last-name of a person. Another application is CSV(Comma Separated Files). We use s
7 min read
Join Elements of a Set into a String in Python
You might have encountered situations where you needed to join the elements of a set into a string by concatenating them, which are separated by a particular string separator. Let's say we want to convert the set {"GFG", "courses", "are", "best"} into a string with a space between each element that results in "GFG courses are best". In this article
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 | Join tuple elements in a list
Nowadays, data is something that is the backbone of any Machine Learning technique. The data can come in any form and its sometimes required to be extracted out to be processed. This article deals with the issue of extracting information that is present in tuples in list. Let's discuss certain ways in which this can be performed. Method #1: Using j
6 min read
Practice Tags :