如果在python中满足条件,则替换字符串

我有一个看起来像这样的文件,如果文件中的文件名 ="3ghi"(我可以是 "3ghi" 或 5"ghi" ),那么条件大于 4 应该更改为“新”并且条件 <=2 应该改为“公平”。我在下面添加了我的代码,替换命令有效,但我的 if 循环不好。请帮忙。


Input:

<code=report docket="3ghi" parse=20>

    <items="20" product="abc" condition="9">

    <items="50" product="xyz" condition="8">

    <items="" product="mno" condition="2">


Output:

<code=report docket="3ghi" parse=20>

    <items="20" product="abc" condition="new">

    <items="50" product="xyz" condition="new">

    <items="" product="mno" condition="fair">


with open(("test.txt",'r') as new:

   readin = new.read

   if "docket =3ghi" == True:

        readin.replace('condition="4-100"', 'condition="new"')

        readin.replace('condition="1-2"', 'condition="fair"')

        x.write(readin)


慕哥6287543
浏览 277回答 3
3回答

温温酱

让我们分解一下您当前的陈述:if "docket = 3ghi" == True:非空字符串的计算结果类似于True,但不完全是 True。True是一个布尔值,所以你问“这个字符串是一个布尔值吗?” 那总是False:"somestr" == True# False修复它以检查字符串是否是in文件的一部分。例如:with open(("test.txt",'r') as new:&nbsp; &nbsp; for line in new.read(): # read in the file and iterate&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if "somestr" in line:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# do something注意我还添加了括号,new.read()这样你就不会得到像function doesn't support iteration

幕布斯7119047

第一个问题:readin&nbsp;=&nbsp;new.read您没有调用该方法,您将无法获取文件内容&nbsp;readin第二个问题:if&nbsp;"docket&nbsp;=3ghi"&nbsp;==&nbsp;True:您正在比较字符串是否为True- 它从不True。

30秒到达战场

您需要正确调用该方法才能将文件的全部内容放在readin. 现在你可以replace两次检查也正确的条件with open('test.txt', 'r') as new:&nbsp; &nbsp; readin = new.read()&nbsp; &nbsp; if 'docket="3ghi"' in readin:&nbsp; &nbsp; &nbsp; &nbsp; readin = readin.replace('"I"', '"new"').replace('"II"', '"fair"')&nbsp; &nbsp; &nbsp; &nbsp; # save or print or do whatever you want with readin
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python