按索引顺序替换Python中的字符串 [英] String replace in Python, in sequence, by index

查看:0
本文介绍了按索引顺序替换Python中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手,刚刚开始从YouTube学习Python。我正在尝试编写一个程序,用新的字符串号替换旧的字符串号,但在替换数字时遇到了问题。我想要取代指数(它的专业术语是什么(我不知道))。它可以单向运行,也可以按索引运行。

我的字符串是= (01010110110111011110111101111011110101101101101011011011010101010101010101011101110101110111101)

我想用01110,0110替换010,用00,0000替换00,用0000替换011110,

因此我替换的字符串/输出字符串将如下所示..

(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

推荐答案

我相信这就是您要找的:

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)

这是一段简单的代码,因此不包括任何输入有效性检查,但它显示了基本概念。根据您的情况/偏好进行相应的编辑

这篇关于按索引顺序替换Python中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆