简体   繁体   中英

tuple to string formatting

After a certain calculation i am getting an output like:

('      ','donor','       ','distance')  

('      ','ARG','A','43','  ','3.55')  
('      ','SOD','B',93', '  ','4.775')  
('      ','URX','C',33', '   ','3.55')

while i was intending to get like:

  donor            distance
    ARG A 43         3.55
    SOD B 93         4.77
    URX C 33         3.55

the thing what i am getting is a tuple, but i am very confused on how to make this tuple into a well formatted look as per my desire. Please give some idea... thank you.

Use str.join() on each tuple:

' '.join(your_tuple)

before printing.

You can use a for-loop and str.join :

lis = [
    ('     ','donor','    ','distance'),
    ('      ','ARG','A','43','  ','3.55'),
    ('      ','SOD','B','93', '  ','4.775'),
    ('      ','URX','C','33', '  ','3.55')
]

for item in lis:
    print " ".join(item)

Output:

 donor      distance
   ARG A 43    3.55
   SOD B 93    4.775
   URX C 33    3.55

If your data looks like this

data = [
    ('      ', 'donor', '       ', 'distance'),
    ('      ', 'ARG', 'A', '43', '       ', '3.55'),
    ('      ', 'SOD', 'B', '93', '       ', '4.775'),
    ('      ', 'URX', 'C', '33', '       ', '3.55')
]

Then you can just

print '\n'.join(map(' '.join, data))

It sounds like you want to use format strings . For example, assuming that you are not storing padding strings in your items:

print "{0} {1} {2}   {3:>10.2f}".format(*item)

You can specify the exact format (including width and alignment) of each field of the record in the format string. In this example, the fourth string is right-aligned to fit into 10 characters, with 2 digits displayed to the right of the decimal point.

Example using your data:

>>> x = (('      ','ARG','A','43','  ','3.55'),('      ','SOD','B','93', '  ','4.775'),('      ','URX','C','33', '   ','3.55'))
>>> f = "{0:3s}{1:1s}{2:2s} {3:>10.3f}"
>>> for item in x: print f.format(item[1], item[2], item[3], float(item[5]))
...
ARGA43      3.550
SODB93      4.775
URXC33      3.550

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM