python替换整行_Python:在一行中搜索STR1并用STR2替换整行

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

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

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)

解决方案

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值