python3.5.2从fi中删除所有匹配字符

2024-06-26 14:02:02 发布

您现在位置:Python中文网/ 问答频道 /正文

给出以下示例,如何从具有以下内容的文件中删除所有“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","")

Tags: 文件in示例forindexwithlineopen
3条回答

你可以试试这个:

import re
data = open("testfisier").read()
final_data = re.sub('a+', '', data)

没有任何更改,因为您没有将其写回文件

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", ""))

尝试使用regexp替换。例如,假设您已读入该字符串并将其命名为\u字符串

import re re.sub('a','',a_string,'') 这将是许多可能的解决办法之一

希望这有帮助

相关问题 更多 >