Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a list of tuples with no brackets in Python

Tags:

I'm looking for a way to print elements from a tuple with no brackets.

Here is my tuple:

mytuple = [(1.0,),(25.34,),(2.4,),(7.4,)] 

I converted this to a list to make it easier to work with

mylist = list(mytuple) 

Then I did the following

for item in mylist:     print(item.strip()) 

But I get the following error

AttributeError: 'tuple' object has no attribute 'strip' 

Which is strange because I thought I converted to a list?

What I expect to see as the final result is something like:

1.0, 25.34, 2.4, 7.4 

or

1.0, ,23.43, ,2.4, ,7.4  
like image 918
Boosted_d16 Avatar asked Oct 01 '13 09:10

Boosted_d16


People also ask

How can I print a list of tuples 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.

How do I print a list 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!

How do I remove a tuple bracket from a list in Python?

Using join function to remove brackets from a list in Python. join() is a built-in function in python. This method takes all the elements from a given sequence. Then it joins all the elements and prints them into a single element.


2 Answers

mytuple is already a list (a list of tuples), so calling list() on it does nothing.

(1.0,) is a tuple with one item. You can't call string functions on it (like you tried). They're for string types.

To print each item in your list of tuples, just do:

for item in mytuple:     print str(item[0]) + ',' 

Or:

print ', ,'.join([str(i[0]) for i in mytuple]) # 1.0, ,25.34, ,2.4, ,7.4 
like image 157
TerryA Avatar answered Sep 30 '22 17:09

TerryA


You can do it like this as well:

mytuple = (1,2,3) print str(mytuple)[1:-1] 
like image 38
Bertrand Poirot Avatar answered Sep 30 '22 17:09

Bertrand Poirot