Borislav Hadzhiev
Last updated: Jul 2, 2022
Photo from Unsplash
To convert a tuple to a string without parenthesis:
str.join()
method on a string separator.join()
method.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.
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()
.
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.
my_tuple = ('a', 'b', 'c') my_str_1 = '-'.join(my_tuple) print(my_str_1) # 👉️ 'a-b-c'
If you only want to exclude the parenthesis, call the join()
method on a
string that contains a comma and a space.
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.
my_tuple = ('a', 'b', 'c') my_str_1 = ''.join(my_tuple) print(my_str_1) # 👉️ 'abc'