【问题标题】:left padding with python用python左填充
【发布时间】:2021-12-10 00:17:49
【问题描述】:

我有以下 100000 个条目的数据和链接组合

dn:id=2150fccc-beb8-42f8-b201-182a6bf5ddfe,ou=test,dc=com
link:545214569

dn:id=ffa55959-457d-49e6-b4cf-a34eff8bbfb7,ou=test,dc=com
link:32546897

dn:id=3452a4c3-b768-43f5-8f1e-d33c14787b9b,ou=test,dc=com
link:6547896541

如果链接的值小于 10,我正在尝试在 python 2.7 中编写一个程序来添加左填充零。

例如:

545214569  --> 0545214569
32546897   --> 0032546897

你能指导我以下程序有什么问题吗:

    with open("test.txt", "r") as f:
     line=f.readline()
     line1=f.readline()
     wordcheck = "link"
     wordcheck1= "dn"
     for wordcheck1 in line1:
         with open("pad-link.txt", "a") as ff:
             for wordcheck in line:
                 with open("pad-link.txt", "a") as ff:
                     key, val = line.strip().split(":")
                     val1  = val.strip().rjust(10,'0')
                     line = line.replace(val,val1)
                     print (line)
                     print (line1)
                     ff.write(line1 + "\n")
                     ff.write('%s:%s \n' % (key, val1))

【问题讨论】:

标签: python python-2.7 zero-padding


【解决方案1】:

我不知道你为什么要打开很多次。无论如何,打开 1 次,然后对于每一行,由 : 分割。列表中的最后一个元素是数字。然后你知道数字应该一致的长度是多少,比如 150,然后使用 zfill 填充 0。然后使用 join 将行放回

for line in f.readlines():
  words = line.split(':')
  zeros = 150-len(words[-1])
  words[-1] = words[-1].zfill(zeros)
  newline = ':'.join(words)
  # write this line to file 

【讨论】:

    【解决方案2】:

    您的for wordcheck1 in line1:for workcheck in line: 没有按照您的想法行事。他们一次一个字符遍历行并将该字符分配给工作检查变量。

    如果您只想将输入文件更改为前导零,则可以简化为:

    import re
    
    # Read the whole file into memory
    with open('input.txt') as f:
        data = f.read()
    
    # Replace all instances of "link:<digits>", passing the digits to a function that
    # formats the replacement as a width-10 field, right-justified with zeros as padding.
    data = re.sub(r'link:(\d+)', lambda m: 'link:{:0>10}'.format(m.group(1)), data)
    
    with open('output.txt','w') as f:
        f.write(data)
    

    输出.txt:

    dn:id=2150fccc-beb8-42f8-b201-182a6bf5ddfe,ou=test,dc=com
    link:0545214569
    
    dn:id=ffa55959-457d-49e6-b4cf-a34eff8bbfb7,ou=test,dc=com
    link:0032546897
    
    dn:id=3452a4c3-b768-43f5-8f1e-d33c14787b9b,ou=test,dc=com
    link:6547896541
    

    【讨论】:

      【解决方案3】:

      在 Python 中填充值的常用 Python 方法是使用字符串格式和 Format Specification Mini Language

      link = 545214569
      print('{:0>10}'.format(link))
      

      【讨论】:

      • 我不认为填充功能有问题。问题在于循环遍历行并以相同的顺序将 dn 和填充值添加到文件中而不会丢失其索引
      猜你喜欢
      • 2012-08-07
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2013-05-10
      • 2014-10-24
      • 1970-01-01
      相关资源
      最近更新 更多