Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python .replace()索引用作循环的变量_Python_Replace - Fatal编程技术网

Python .replace()索引用作循环的变量

Python .replace()索引用作循环的变量,python,replace,Python,Replace,大家好 我是初学者,我找不到答案: one = [" January ", " February ", " March ", " April ", " May ", \ " June ", " July ", " August ", " September ", " October "

大家好 我是初学者,我找不到答案:

one = [" January ", " February ", " March ", " April ", " May ", \
        " June ", " July ", " August ", " September ", " October ", \
        " November ", " December ", "   ", "IPS", "COL", "BRT"]

two = ["/01/", "/02/", "/03/", "/04/", "/05/", "/06/", "/07/", "/08/",\
        "/09/", "/10/", "/11/", "/12/", ",", "", "", ""]

a = len(one)     
b = len(two)

while a>0:
    text = open("database.txt", "r")
    text = ''.join([i for i in text]).replace(one[a], two[a])
    x = open("new_database.txt","w")
    x.writelines(text)
    x.close()
    a = a - 1
错误是:

    text = ''.join([i for i in text]).replace(one[a], two[a])
IndexError: list index out of range

如果有人能帮忙,非常感谢

错误是因为列表索引是从零开始的,因此
one
的有效索引是
0
len(one)-1
。由于您将
a
初始化为
len(one)
,因此它超出了范围

但是,您不应该手动分配索引变量并减少它们,而应该只循环遍历列表元素。您可以使用
zip()
并行循环浏览两个列表

这里有一个更好的写作方法:

with open("database.txt", "r") as indb, open("new_database.txt", "w") as outdb:
    for line in indb:
        for old, new in zip(one, two):
            line = line.replace(old, new)
        outdb.write(line)

如果
a
one
的长度,则
a
超出
one
的范围,并且
one[a]
将导致索引错误。长度
a
列表的索引必须严格小于
a
。列表索引从0到
len-1
。因此,您需要执行
a=len(one)-1
除了Khelwood之外,python还从0索引列表。这意味着,当a>=0时,您也应该执行
,或者您可以对in范围(len(one)-1,-1,-1)使用
,每次通过循环,您都要在原始
数据库.txt
上执行替换,而不是先前替换的结果。噢,哇!我对编程很不熟悉,但是…很小的一步。谢谢