reposition a column

MRAB python at mrabarnett.plus.com
Thu Nov 26 12:04:55 EST 2009


Francesco Pietra wrote:
> Hi:
> 
> script now used:
> 
> # Sample line
> # Slice indexes cut to the left of the corresponding item index
> #           1         2         3         4         5         6
> # 012345678901234567890123456789012345678901234567890123456789012345 ...
> # ATOM      1  W     W     1       0.690  35.960  33.300  1.00  0.00
> 
> data = open('out.2.5.2.5.2.0.pdb', 'r')
> outp = open('rect.out.2.5.2.5.2.0.pdb', 'w')
> 
> for L in data:
>   if L[19] == 'W':
>     L = L[ : 17] + L[19] + L[18] + ' ' + L[20 : ]
>   outp.write(L)
> 
> francesco at tya64:~/tmp$ python MRAB.py
> Traceback (most recent call last):
>  File "MRAB.py", line 11, in <module>
>    if L[19] == 'W':
> IndexError: string index out of range
> francesco at tya64:~/tmp$
> 
> Unfortunately, in my hands gmail plaint text is like that. Actually,
> the second 'W' is 19.
> 
The code is assuming that the lines are all at least 19 characters long;
if a line is shorter then there's no position 19!

Try checking the line length too:

    if len(L) >= 19 and L[19] == 'W':

Alternatively:

    if L[19 : 20] == 'W':

(If the line is too short then L[19 : 20] will return ''.)



More information about the Python-list mailing list