Convert a tuple to a string in Python


Borislav Hadzhiev

Last updated: Jul 2, 2022


Photo from Unsplash

Convert a tuple to a string in Python #

To convert a tuple to a string:

  1. Call the str.join() method on a string separator.
  2. Pass the tuple to the join() method.
  3. The result will be a string containing the tuple elements separated by the provided separator.
my_tuple = ('x', 'y', 'z') # 👇️ with space separator my_str = ' '.join(my_tuple) print(my_str) # 👉️ 'x y z' # 👇️ without separator print(''.join(my_tuple)) # 👉️ 'xyz' # 👇️ with hyphen separator print('-'.join(my_tuple)) # 👉️ 'x-y-z'

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your tuple contains numbers, or other types, convert all of the values to string before calling join().
my_tuple = ('x', 2, 'y', 4, 'z', 6) my_str = ', '.join(map(str, my_tuple)) print(my_str) # 👉️ 'x, 2, y, 4, z, 6'

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We used the function to convert each element in the tuple to a string, before passing the items to the str.join() method.

The string the join() method is called on is used as the separator between the elements.
my_tuple = ('x', 'y', 'z') print('-'.join(my_tuple)) # 👉️ 'x-y-z'

If you need to join the elements of the tuple with spaces, call the method on a string that contains a space.
my_tuple = ('x', 'y', 'z') print(' '.join(my_tuple)) # 👉️ 'x y z'

Similarly, you can use a newline (\n) to join the elements of the tuple with a newline character.
my_tuple = ('x', 'y', 'z') my_str = '\n'.join(my_tuple) # x # y # z print(my_str)

If you don't need a separator and just want to join the tuple's elements into a string, call the join() method on an empty string.
my_tuple = ('x', 'y', 'z') my_str = ''.join(my_tuple) print(my_str) # 👉️ 'xyz'
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.