PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, September 17, 2022

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

 September 17, 2022     list, printing, python, tuples     No comments   

Issue

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 

Solution

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


Answered By - TerryA
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing