【问题标题】:Remove two first character of line if match (Python)如果匹配则删除行的两个第一个字符(Python)
【发布时间】:2022-11-22 22:20:55
【问题描述】:

我有一个大文本文件,内容格式如下,我想删除两个第一个字符 11,我尝试通过不知道如何继续我的代码进行搜索。寻求帮助。谢谢

文件.txt

11112345,67890,12345

115432,a123q,hs1230

11s1a123,qw321,98765321

342342,121sa,12123243

11023456,sa123,d32acas2

我的代码

import re

with open('in.txt') as oldfile, open('out.txt', 'w') as newfile:
    for line in oldfile:
        removed = re.sub(r'11', '', line[:2]):
            newfile.write(removed)

预期结果:

112345,67890,12345

115432,a123q,hs1230

s1a123,qw321,98765321

342342,121sa,12123243

023456,sa123,d32acas2

【问题讨论】:

  • 在您的预期结果中,第二行不应该是 5432,a123q,hs1230 吗?

标签: python python-3.x


【解决方案1】:

这是一个易于阅读的解决方案的建议,不使用我在这里发现有点麻烦的正则表达式(但这显然是个人意见):

with open('in.txt', 'r') as oldfile, open('out.txt', 'w') as newfile:
    for line in oldfile:
        newfile.write(line[2:] if line.startswith('11') else line)

【讨论】:

    猜你喜欢
    • 2017-07-06
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 2020-05-03
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多