strip part of string

John Machin sjmachin at lexicon.net
Sun May 10 11:52:51 EDT 2009


On May 11, 1:18 am, Francesco Pietra <chiendar... at gmail.com> wrote:
> Hi:
> I would like to delete everything from column 54 on for each line
> beginning with "ATOM". In the example in the attachment (sorry for the
> attachment; I found no way with Google mail to have plain text mail)

Many of your audience won't have seen your quite unnecessary
attachment; you could have in-lined the text just like this:
[except that I've deleted empty lines, and chopped some irrelevant
stuff off the right hand end of some lines so that line-wrapping won't
confuse anybody any more than they are already :-)
]

8<---
# Sample line
#           1         2         3         4         5
# 012345678901234567890123456789012345678901234567890123456789
# ATOM     49  NH1 ARG    84      84.628  41.570  44.395  0.00
data = open('rec.crg', 'r')
outp = open('rec.strip.crg', 'w')
for L in data:
   if L[3] == 'M':
     L = L[:55] ???????
   outp.write(L)
8<---

> the new line would become:
>
> ATOM     49  NH1 ARG    84      84.628  41.570  44.395
>
> without any blank space to the right. . Everything else should remain
> at its original column. I have been looking for ???? statement, unable
> (my big fault ) to find a right one. I tried with slices % but it
> becomes unnecessarily complex.

You wish to retain 54 characters, but are retaining 55. You need a
newline on the end of the line. So the statement
    L = L[:55]
should be
    L = L[:54] + '\n'
You may wish to precede that with
    assert len(L) >= 54
You may wish to change
    if L[3] == 'M':
to
    if L.startswith('ATOM'):
to accord with your requirements statement.

HTH,
John



More information about the Python-list mailing list