Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python string isdecimal() Method
Next article icon

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

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

Joining a List of Strings

In below example, we usejoin() method to combine alist of strings into asingle stringwith each string separated by aspace.

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

Output
Hello world from Python

Syntax of join()

separator.join(iterable)

Parameters:

  • separator:The string placed between elements of the iterable.
  • iterable: A sequence of strings (e.g., list, tuple etc) to join together.

Return Value:

  • Returns a single string formed by joining all elements in the iterable, separated by the specified separator
  • If the iterable contains any non-string values and it raises aTypeError exception.

Examples of join() Method on Different Data Types

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

Using join() with Tuples

Thejoin() method works with any iterable containing strings, includingtuples.

Python
s=("Learn","to","code")# Separator "-" is used to join stringsres="-".join(s)print(res)

Output
Learn-to-code

Using join() with set

In this example, we are joining set of String.

Python
s={'Python','is','fun'}# Separator "-" is used to join stringsres='-'.join(s)print(res)

Output
Python-is-fun

Note:Sincesets 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 thejoin()method with adictionary, it will only join thekeys, not the values. This is becausejoin()operates on iterables of strings and the default iteration over a dictionary returns itskeys.

Python
d={'Geek':1,'for':2,'Geeks':3}# Separator "_" is used to join keys into a single stringres='_'.join(d)print(res)

Output
Geek_for_Geeks

Python String join() Method

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp