简体   繁体   中英

New to Python: Replacing a string by its position in a line

Let's say I got a file with three lines of this structure:

foo
Black sheep: 500
bar

What I'd like to do is an iteration to change "Black sheep: 500" to 600, 700 and so on, replacing the old one. I can think of a way of doing it by search&replace, but I'm looking for a more elegant way by replacing a certain position (here pos.3) within the line.

For example, in awk/shellscripting, it works like this:

cat filename | awk '$1 ~ /Black:/ { print ($1, $2, 600); next }; { print $0 }'

awk looks for "Black" in the file and prints the words number one, number two and 600 as well as the rest of the file.

Is there something similar in Python?

Thank you

We can simply mimick the awk behaviour in a couple of lines :)

for line in lines:
    if line.startswith('Black'):
        line_parts = line.split()
        print line_parts[0], line_parts[1], 600
    else:
        print line

Cause that's basically what awk does, split on whitespace.

>>> for line in open("file"):
...     sl=line.split()
...     if "Black" in sl[0] :
...         sl[2]="600"
...         line=' '.join(sl)
...     print line.rstrip()
...
foo
Black sheep: 600
bar

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