Convert a tuple to a string without parenthesis in Python

avatar

Borislav Hadzhiev

Last updated: Jul 2, 2022

banner

Photo from Unsplash

Convert a tuple to a string without parenthesis in Python #

To convert a tuple to a string without parenthesis:

  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.
main.py
my_tuple = (1.1, 2.2, 3.3) # 👇️ with space separator my_str_1 = ' '.join(map(str, my_tuple)) print(my_str_1) # 👉️ '1.1 2.2 3.3' # 👇️ with comma and space seprator my_str_2 = ', '.join(map(str, my_tuple)) print(my_str_2) # 👉️ '1.1, 2.2, 3.3'

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.

The tuple in the example contains integers, so we had to use the map() function to convert the integers to strings before calling join().

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

If your tuple contains strings, omit the call to map().

main.py
my_tuple = ('a', 'b', 'c') my_str_1 = ' '.join(my_tuple) print(my_str_1) # 👉️ 'a b c'

The string the join() method is called on is used as the separator between the elements.

main.py
my_tuple = ('a', 'b', 'c') my_str_1 = '-'.join(my_tuple) print(my_str_1) # 👉️ 'a-b-c'
If you need to join the elements of the tuple with spaces, call the method on a string that contains a space.

If you only want to exclude the parenthesis, call the join() method on a string that contains a comma and a space.

main.py
my_tuple = ('a', 'b', 'c') my_str_1 = ', '.join(my_tuple) print(my_str_1) # 👉️ 'a, b, c'

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.

main.py
my_tuple = ('a', 'b', 'c') my_str_1 = ''.join(my_tuple) print(my_str_1) # 👉️ 'abc'
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.