简体   繁体   English

Python的新功能:通过在行中的位置替换字符串

[英]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. 我想做的是将“ Black Sheep:500”更改为600、700等的迭代,以替换旧的。 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. 我可以想到一种通过search&replace进行操作的方法,但是我正在寻找一种更优雅的方法,方法是替换行中的某个位置(此处为pos.3)。

For example, in awk/shellscripting, it works like this: 例如,在awk / shellscripting中,它的工作方式如下:

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. awk在文件中查找“ Black”,并打印单词“一”,“第二”和“ 600”以及文件的其余部分。

Is there something similar in Python? Python中有类似的东西吗?

Thank you 谢谢

We can simply mimick the awk behaviour in a couple of lines :) 我们可以简单地模仿两行的awk行为:)

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. 原因基本上是awk所做的,在空白处分割。

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM