我的新手剛開始從 YouTube 學習 Python,我正在嘗試制作一個程式來用新字串數字替換舊字串數字,并在替換數字時遇到問題。想要替換索引,(它的技術術語是什么(我不知道))。它可以通過一個方向或索引。
我的字串是 = (01010110110111011110111101111011110101101101101011011011010101010101010101011101110101110111101)
我想用 0、0110 替換 010,用 00、01110、000 和 011110 替換 0000,
所以我替換的字串/輸出字串將是這樣的..
(01 0011 0001111 00001111 00001 0011 001 0011 001 01 01 01 01 000111 0111 00001)
根據我的代碼,它花費了太多時間(僅 8MB 檔案就花費了近 2-3 個小時。
with open('1.txt', 'r') as f:
newstring = ''
old_list = ['010', '0110', '01110', '011110']
new_list = ['0', '00', '000', '0000']
while True:
try:
chunk = f.read()
except:
print('Error while file opening')
if chunk:
n = len(chunk)
i = 0
while i < n:
flag = False
for j in range(6, 2, -1):
if chunk[i:i j] in old_list:
flag = True
index = old_list.index(chunk[i:i j])
newstring = newstring new_list[index]
i = i j
break
if flag == False:
newstring = newstring chunk[i]
i = i 1
newstring=''.join((newstring))
else:
try:
f = open('2xx.txt', "a")
f.write("01" newstring)
f.close()
except:
print('Error While writing into file')
break
uj5u.com熱心網友回復:
我相信這就是你要找的:
old_str = "01010110110111011110111101111011110101101101101011011011010101010101010101011101110101110111101"
split_str = old_str.split("0") # split by 0 delimiter
res = ""
for idx, each in enumerate(split_str):
if idx % 2 != 0: # odd index, turn however many 1's into 0's
res = "0" * len(each)
else:
res = each
print(res)
這是簡單的代碼,所以它不包括任何輸入有效性檢查,但它顯示了基本概念。根據您的情況/偏好進行相應編輯
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368339.html
