Python .join()
In Python, the .join()
method concatenates all items from an iterable into a single string. It’s especially useful when there is a need to combine multiple string elements with a specific separator, like commas, spaces, or newlines.
Syntax
The .join()
method is called on a separator
string:
string.join(iterable)
Parameters:
- The
separator
can be any string, even an empty one, and is placed between each element from theiterable
. - The
iterable
is any object that can be iterated over like tuples or lists. All values of theiterable
must be strings.
Return value:
The .join()
method returns a new string containing the concatenated result.
Example 1: Joining a List of Words with Space
This example joins the elements of the fruits
list with a single space (" "
) in between:
fruits = ["Apples", "Bananas", "Blueberries"]combined = " ".join(fruits)print(combined)
Here is the output:
Apples Bananas Blueberries
Example 2: Using a Hyphen as Separator
This example uses .join()
to append elements of a tuple with a hyphen ("-"
) as separator:
vehicles = ("bicycle", "car", "moped", "truck")joined = "-".join(vehicles)print(joined)
Here is the output:
bicycle-car-moped-truck
Codebyte Example: Joining Characters in a String
In this example, the string "hello"
is treated as an iterable of characters, which are joined using "."
as a separator:
Here is the output:
h.e.l.l.o
Frequently Asked Questions
1. Can I use .join()
with numbers?
No, all elements must be strings. If you try to join a list of integers using .join()
, you’ll get a TypeError
. Use str()
or a list comprehension to convert them first:
numbers = [1, 2, 3]joined = "-".join(str(num) for num in numbers)
2. What happens if the list passed to .join()
is empty?
If the iterable is empty, .join()
returns an empty string:
print(",".join([])) # Output: ''
3. Is .join()
faster than using +
in a loop?
Yes. Using .join()
is much faster and more memory-efficient than concatenating strings with +
in a loop. It’s the recommended way to concatenate many strings.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours