[Tutor] creating a regularly placed fields in a line

Prasad, Ramit ramit.prasad at jpmorgan.com
Wed Apr 25 17:57:03 CEST 2012


> I wrote a small piece of code (given below). The aim is to take each line
> in a file, split the fields, replace the first four fields and then write
> the new lines in a output file. The input and output are given in the
> attached file. The output contains fields which are irregularly placed
> depending up on the size of the field. I am thinking to fix the size of
> each field. Kindly provide me some way on how i can do the same or a
> better way to fix placement of fields.
> 
> with open('tmp') as tp:
>     for line in tp:
>         line=line.split()
>         p1=atm_type[line[0]];p2=atm_type[line[1]]
>         p3=atm_type[line[2]];p4=atm_type[line[3]]
>         new='\t'.join(line[4:10])
>         bond.write('   %s\t%s\t%s\t%s\t%s\n' % (p1,p2,p3,p4,new) )

Taking a look at your output file leads me think that it is 
not really meant to be human readable. If it is only for a 
program to use, then I would just make it comma separated
using the csv module. If you are intending to make it readable
to humans, I would suggest looking at string formatting. 
It is better than tabbing since most clients show tabs a 
little differently and a tab may still cause irregular
columns if you have a large difference in each row's
column size. The formatting mini-language can be a little 
complex but luckily the guide is useful.
http://docs.python.org/library/string.html#format-specification-mini-language 

The examples on that page are useful and I think what you 
want is quoted below.
"
Aligning the text and specifying a width:
>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'
"

Not really sure how to do the equivalent with % substitution.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list