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?
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.
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.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With