Yandex

Python String join() Method – Combine Strings Easily


Python String join() Method

The join() method in Python is used to combine a list of strings into one single string, with a specified separator between each element.

It is called on a string (used as a separator) and passed an iterable (like a list or tuple) of strings.

Syntax

separator_string.join(iterable_of_strings)

Parameters:

  • separator_string – The string that will be placed between each item (e.g., space, comma, hyphen).
  • iterable_of_strings – A list, tuple, or other iterable containing strings.

Returns:

  • A new string that is the concatenation of all strings in the iterable, separated by the separator.

Example 1: Join List with Spaces

words = ['Python', 'is', 'awesome']
sentence = ' '.join(words)
print(sentence)
Python is awesome

Example 2: Join List with Hyphens

date_parts = ['2025', '05', '14']
date_string = '-'.join(date_parts)
print(date_string)
2025-05-14

Example 3: Join Tuple with Commas

items = ('apple', 'banana', 'cherry')
result = ', '.join(items)
print(result)
apple, banana, cherry

Use Case: Why Use join()?

  • Efficient way to concatenate many strings.
  • Useful in formatting output (like CSVs, dates, or sentences).
  • Cleaner and faster than using a loop with +.

Common Mistakes

  • All elements in the iterable must be strings. Mixing types (e.g., int or float) will raise a TypeError.

Incorrect Example:

print(','.join(['Python', 3]))
TypeError: sequence item 1: expected str instance, int found

Interview Tip

join() is often used in questions involving string formatting or list manipulation. It’s faster and more efficient than using loops for string concatenation.

Summary

  • join() combines elements of an iterable into one string.
  • The string it is called on becomes the separator.
  • All elements in the iterable must be strings.

Practice Problem

Join a list of numbers (converted to strings) with a colon ":" as a separator.

numbers = [1, 2, 3, 4, 5]
# Convert each number to string first
str_numbers = [str(num) for num in numbers]
result = ':'.join(str_numbers)
print(result)
1:2:3:4:5


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M