A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-string-join-method/ below:

Python String join() Method - GeeksforGeeks

Python String join() Method

Last Updated : 12 Nov, 2024

The join() method in Python is used to concatenate the elements of an iterable (such as a list, tuple, or set) into a single string with a specified delimiter placed between each element.

Lets take a simple example to join list of string using join() method.

Joining a List of Strings

In below example, we use join() method to combine a list of strings into a single string with each string separated by a space.

Python
a = ['Hello', 'world', 'from', 'Python']
res = ' '.join(a)
print(res)  

Output
Hello world from Python
Syntax of join()

separator.join(iterable)

Parameters: Return Value: Examples of join() Method on Different Data Types

Below are examples of how join() method works with different data types.

Using join() with Tuples

The join() method works with any iterable containing strings, including tuples.

Python
s = ("Learn", "to", "code")

# Separator "-" is used to join strings
res = "-".join(s)
print(res)
Using join() with set

In this example, we are joining set of String.

Python
s = {'Python', 'is', 'fun'}

# Separator "-" is used to join strings
res = '-'.join(s)
print(res) 

Note: Since sets are unordered, the resulting string may appear in any order, such as "fun is Python" or "Python is fun".

Using join() with Dictionary

When using the join() method with a dictionary, it will only join the keys, not the values. This is because join() operates on iterables of strings and the default iteration over a dictionary returns its keys.

Python
d = {'Geek': 1, 'for': 2, 'Geeks': 3}

# Separator "_" is used to join keys into a single string
res = '_'.join(d)

print(res)

Python String join() Method


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4