Python:在一行中搜索STR1并用STR2替换整行 [英] Python: search for a STR1 in a line and replace the whole line with STR2

查看:276
本文介绍了Python:在一行中搜索STR1并用STR2替换整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我需要在其中搜索 STR1 并替换包含 STR2 的整行。例如, file1 包含以下数据

I have a file in which I need to search for STR1 and replace the whole line containing STR2. For example the file1 contains the following data

Name: John
Height: 6.0
Weight: 190
Eyes: Blue

我需要在上面的文件中搜索 Name ,然后用名称:Robert 替换整行。我可以在sed中轻松完成这项工作

I need to search for Name in the above file and then replace the whole line with Name: Robert. I can accomplish this easily in sed as

sed -i 's/.*Name.*/Name:Robert/' file1

但是如何在python中获得相同的结果。例如,我可以使用 fileinput 将一个字符串替换为另一个字符串,如下所示

But how to get the same in python. For example I can replace one string with another string using fileinput as follows

#! /usr/bin/python
import fileinput
for line in fileinput.input("file1", inplace=True):
    # inside this loop the STDOUT will be redirected to the file
    # the comma after each print statement is needed to avoid double line breaks
    print line.replace("Name: John", "Name: Robert"),

如何修改上述代码以替换整行,使用'*'替换所有行在文件中即使有搜索条件(如果名称在行

How to modify the above code to replace the whole line, using '*' replaces all the lines in the file even with a search condition (if "Name" in line)

推荐答案

您可以使用 string.find()来确定字符串是否在另一个字符串中。 相关的Python文档

You can use string.find() to determine if a string is within another string. Related Python docs.

#! /usr/bin/python
import fileinput
for line in fileinput.input("file1", inplace=True):
    if line.find("Name:") >= 0:
        print "Name: Robert"
    else:
        print line[:-1]

这篇关于Python:在一行中搜索STR1并用STR2替换整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆