Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

python - .replace() index use as variable for a loop

hi everyone! I am a beginner and I can't find answer for this:

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

the error is:

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

if anyone can help, much appreciated!

question from:https://stackoverflow.com/questions/65893597/replace-index-use-as-variable-for-a-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error is because list indexes are zero-based, so the valid indexes of one are 0 through len(one)-1. Since you initiaze a to len(one), it's outside the range.

But instead of manually assigning index variables and decrementing them, you should just loop through the list elements. You can use zip() to loop through two lists in parallel.

Here's a better way to write it:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...