开发者

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

开发者 https://www.devze.com 2023-01-18 01:02 出处:网络
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

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&am开发者_如何学编程p;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
0

精彩评论

暂无评论...
验证码 换一张
取 消