我有以下 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
我正在嘗試在 python 2.7 中撰寫一個程式,如果鏈接的值小于 10 ,則添加左填充零。
例如:
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))
uj5u.com熱心網友回復:
在 Python 中填充值的常用 Pythonic 方法是使用字串格式和格式規范迷你語言
link = 545214569
print('{:0>10}'.format(link))
uj5u.com熱心網友回復:
你for wordcheck1 in line1:并for workcheck in line:沒有按照你的想法去做。他們在行上一次迭代一個字符,并將該字符分配給 workcheck 變數。
如果您只想將輸入檔案更改為具有前導零,則可以簡化為:
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
uj5u.com熱心網友回復:
我不知道你為什么要打開很多次。無論如何,打開 1 次,然后對于每一行,用 : 分割。串列中的最后一個元素是數字。然后你知道數字的長度應該一致 b,比如 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334981.html
標籤:Python python-2.7 零填充
上一篇:如何使用串列呼叫函式?
下一篇:決議明文API回應
