鉴于以下示例,我如何从具有以下内容的文件中删除所有“a”字符:
asdasdasd \n d1233sss \n aaa \n 123
我写了以下解决方案,但它不起作用:
with open("testfisier","r+") as file:
for line in file:
for index in range(len(line)):
if line[index] is "a":line[index].replace("a","")
答案 0 :(得分:2)
没有任何更改,因为您没有将其写回文件。
with open("testfisier", "r+") as file:
for line in file:
for index in range(len(line)):
if line[index] is "a":
replace_file = line[index].replace("a", "")
# Write the changes.
file.write(replace_file)
或者:
with open("testfisier", "r+") as f:
f.write(f.read().replace("a", ""))
答案 1 :(得分:1)
尝试使用regexp替换。例如,假设您已读入字符串并将其命名为a_string
import re
re.sub('a','',a_string,'')
这将是许多可能的解决方案之一。
希望这有帮助!
答案 2 :(得分:1)
你可以试试这个:
import re
data = open("testfisier").read()
final_data = re.sub('a+', '', data)
答案 3 :(得分:0)
您可以在长字符串上调用replace
。无需在单个字符上调用它。此外,replace不会更改字符串,但会返回一个新字符串:
with open("testfisier", "r+") as file:
text = file.read()
text = text.replace("a", "") # replace a's in the entire text
file.seek(0) # move file pointer back to start
file.write(text)