Insert character at a fixed position of lines
Peter Otten
__peter__ at web.de
Sat Jul 26 04:08:04 EDT 2008
Francesco Pietra wrote:
> How to insert letter "A" on each line (of a very long list of lines)
> at position 22, i.e., one space after "LEU", leaving all other
> characters at the same position as in the original example:
>
>
> ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04
> 1SG 2
>
> In all lines"ATOM" is constant as to both position and string, while
> "LEU" is constant as to position only, i.e., "LEU" may be replaced by
> three different uppercase letters. Therefore, the most direct
> indication would be position 22.
You insert a string into another one using slices
line = line[:22] + " " + line[22:]
(Python's strings are immutable, so you are not really modifying the old
string but creating a new one)
> Should the script introduce blank lines, no problem. That I know how
> to correct with a subsequent script.
You are probably printing lines read from a file. These lines already end
with a newline, and print introduces a second one. Use the file's write()
method instead of print to avoid that, e. g.:
import sys
for line in sys.stdin:
line = line[:22] + " " + line[22:]
sys.stdout.write(line)
Peter
More information about the Python-list
mailing list