Python String join() Method

Filed Under: Python String

Python string join() method creates a string from an iterable. It joins all the iterable elements with the string as delimiter and returns it.

When to use Python String join() Method?

Some possible use cases are:

  • Creating CSV String from an iterable such as List, Tuple, etc.
  • For logging purpose, get the string representation of the iterable and log into file.
  • Saving an iterable object into a file by converting it to a string.

Syntax of join() Method

The join() method syntax is:

str.join(iterable)

The output is a new string, which we can assign to another variable. We can use List, Tuple, String, and Set as input data types because they are iterables.

Let’s look at some examples of using string join() method.

1. Joining List of Strings to CSV

delimiter = ","

csv_str = delimiter.join(['a', 'b', 'c'])

print(csv_str)  # a,b,c

2. Concatenation of the Strings

tuple_vowels = ('a', 'e', 'i', 'o', 'u')

vowels_str = "".join(tuple_vowels)

print(vowels_str)  # aeiou

We can use join() with an empty string to concatenate all the strings in the iterable.

3. Using join() with Single String as input

str = 'Hello'

print(f'String characters are: {",".join(str)}')

Output:

String characters are: H,e,l,l,o

The string is iterable in Python. So when we pass a single string as join() method input, its characters are the iterable elements.

4. String join() with Set

vowels_set = set(('a', 'e', 'i', 'o', 'u'))

print(" ".join(vowels_set))

Output:

u i e o a

Python set is an unordered collection, so the iteration order is random. You might get a different output in multiple runs.

5. Exception with join()

If the iterable elements are not string, it raises a TypeError.

class Data:
    pass


d1 = Data()
d2 = Data()

list_data = [d1, d2]

print(",".join(list_data))

Output:

TypeError: sequence item 0: expected str instance, Data found

Conclusion

The join() method is useful in creating a string representation from the iterable elements. This method returns a new string and the original string and iterable remains unchanged. We can create CSV string as well as a tab-separated string using this method.

Further Reading

  1. Python String Functions
  2. f-strings in Python
  3. String formatting in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages