How to join list/tuple elements into a single string in Python

About String Join() Method

In Python, the join() is a string method that concatenates (joins) elements of an iterable such as a list or a tuple into a single string.

A specified separator is used to join the elements of an iterable (list or tuple).

Join elements of an iterable using join() method



Join List Elements

1. Create a list with string elements (str_list = ["Apple", "Banana", "Cherry", "Orange"]) where str_list is a variable and ["Apple", "Banana", "Cherry", "Orange"] are elements of list.

2. Apply string join() method with a string separator (str_separator = ", ") and pass the str_list variable as argument to the method. Then assign it to joined_string variable. The code will look like this "str_separator.join(str_list)". Use print() function to print the string.

Please take a closer look at the following example:

Example of joining list elements

Output of the above example
The joined string is: Apple, Banana, Cherry, Orange


Join Tuple Elements

1. Create a tuple with string elements (str_tuple = ("English", "Math", "Physics", "History")) where str_tuple is a variable and ("English", "Math", "Physics", "History") are elements of tuple.

2. Apply string join() method with a string separator (x_str_separator = ", ") and pass the str_tuple variable as argument to the method. Then assign it to joined_tuple_string variable. The code will look like this "joined_tuple_string = x_str_separator.join(str_tuple)". Use print() function to print the string.

Please take a closer look at the following example:

Example of joining tuple elements

Output of the above example
The joined string is: English, Math, Physics, History

Live Code Playground

In the following Python code editor, you can practice the above code by creating more set using different methods. Click on the 'Execute Code' button to execute the code; the executed output will be displayed in the following Python Code Output frame. Practice until you become comfortable and proficient with your code.

Python logo Python Online Editor
Python Code Output