Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print a tuple of tuples without brackets

Tags:

python

tuples

I am trying to print the tuple new_zoo given below without brackets:

zoo=('python','elephant','penguin')
new_zoo=('monkey','camel',zoo)

I know usually we can use ', '.join(...). But because here the new_zoo tuple contains a inside tuple zoo, so when I use ', '.join(new_zoo) it shows:

TypeError: sequence item 2: expected str instance, tuple found

Can anyone help me with this question?

like image 840
Imola Avatar asked Mar 13 '18 20:03

Imola


People also ask

How can I print a tuple without brackets?

You can print a tuple without parentheses by combining the string. join() method on the separator string ', ' with a generator expression to convert each tuple element to a string using the str() built-in function.

Can we write tuple without parentheses?

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). A tuple can also be created without using parentheses.

How do I print a list of elements without brackets?

You can unpack all list elements into the print() function to print each of them individually. Per default, all print arguments are separated by an empty space. For example, the expression print(*my_list) will print the elements in my_list , empty-space separated, without the enclosing square brackets!


1 Answers

The easiest way is to add the tuples instead of nesting them:

>>> new_zoo = ('monkey', 'camel') + zoo

Another way to create a flattened tuple is to use star unpacking (colloquially known as splat sometimes):

>>> new_zoo = ('monkey', 'camel', *zoo)
>>> print(new_zoo)
('monkey', 'camel', 'python', 'elephant', 'penguin')

You can assemble the string directly in this case: ', '.join(new_zoo).

If you need to process a nested tuple, the most general way would be a recursive solution:

>>> new_zoo = ('monkey', 'camel', zoo)
>>> def my_join(tpl):
...    return ', '.join(x if isinstance(x, str) else my_join(x) for x in tpl)
>>> my_join(new_zoo)
monkey, camel, python, elephant, penguin
like image 90
Mad Physicist Avatar answered Sep 28 '22 18:09

Mad Physicist