![](/img/trans.png)
[英]Write a function that removes the first occurrence of a string from another string.
[英]On first occurrence of string write function writes nothing
功能:
def newstr(string, file_name, after):
lines = []
with open(file_name, 'r') as f:
for line in f:
lines.append(line)
with open(file_name, 'w+') as f:
flag = True
for line in lines:
f.write(line)
if line.startswith(after) and flag:
f.write(string+"\n")
flag = False
我正在跑步
newstr('hello', "test.txt", "new code(")
Test.txt內容:
package example.main;
import example
public class Main {
public static void Main() {
new code("<RANDOM>");
new code("<RANDOM>");
}
}
我的期望:
package example.main;
import example
public class Main {
public static void Main() {
new code("<RANDOM>");
hello
new code("<RANDOM>");
}
}
但是,當我運行腳本時,沒有任何變化。
您的行帶有空格縮進 ,例如
new code("<RANDOM>");
該行的開頭有空格。 如果您查看字符串表示形式,將會看到:
>>> repr(line)
' new code("<RANDOM>");\n'
那行不是以'new code('
開頭,而是以' new code('
開頭:
>>> line.startswith('new code(')
False
str.startswith()
不會忽略空格。
刪除空格,或在after
變量中包括空格:
>>> line.strip().startswith('new code(') # str.strip removes whitespace from start and end
True
>>> line.startswith(' new code(')
True
您還可以使用正則表達式來匹配行,因此請使用模式r'^\\s*new code\\('
。
您的錯誤是該行不是以您要查找的文本開頭。 它以" new code("
而不是"new code(
開頭。因此,您需要查找" new code(
或者需要從行中刪除空格,即line.lstrip().startswith(...
順便說一句。 除了使用循環讀取文件外,您還可以說lines = f.readlines()
。
由於IDE正在創建大量空白,因此您需要先剝離它,然后才能使用startswith
因此將其更改為line.lstrip().startswith
以便接下來刪除line.lstrip().startswith
的空白以進行編寫,您可以使用Regex添加這樣,您的新行的空白
f.write(re.search(r"\s*", line).group()+string+"\n")
固定代碼:
import re
def newstr(string, file_name, after):
with open(file_name, 'r') as f:
lines = f.readlines()
with open(file_name, 'w+') as f:
flag = True
for line in lines:
f.write(line)
if line.lstrip().startswith(after) and flag:
f.write(re.search(r"\s*", line).group()+string+"\n")
flag = False
newstr('hello', "test.txt", "new code(")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.