TobyTobyo
TobyTobyo

Reputation: 405

Python not replacing value in list

I'm trying to edit values in a list so I can make this list similar to another list I have elsewhere in my program.

I get a list of values from a document, and want to turn "Off" into "No", and "On" into "Yes", "" into "Null", etc.

However, the following code isn't replacing those values for some reason:

counter = 0
while counter < len(value_list)-1:
    if str(value_list[counter]) in ("", " ", "N/A"):
        value_list[counter] = "Null"
    elif str(value_list[counter]) == "Off":
        value_list[counter] = "No"
    elif str(value_list[counter]) == "On":
        value_list[counter] = "Yes"
    counter += 1
    print counter, value_list[counter]

My output is (I just took snips, since its several hundred lines):

0 ""
1 ""
2 ""
...
7 "Off"
8 "Off"
9 "Off"
10 "Off"
...
556 ""
557 ""

I looked at this post, but using enumerate just gave me the same issue as I have now. Preferably, I want to stick with a counter variable and if/elif/else statements, since I'm one of the few coders in my office, and want others to understand this easily!

Upvotes: 0

Views: 84

Answers (2)

Yuval Ben-Arie
Yuval Ben-Arie

Reputation: 1290

The output you presented here is not possible:

counter = 0
while counter < len(value_list)-1:
    if str(value_list[counter]) in ("", " ", "N/A"):
        value_list[counter] = "Null"
    elif str(value_list[counter]) == "Off":
        value_list[counter] = "No"
    elif str(value_list[counter]) == "On":
        value_list[counter] = "Yes"
    counter += 1
    print counter, value_list[counter]

You first increment counter and only then print. This means you will first output counter as 1.
This also means you print the next position in value_list (which you haven't touched yet).
Also, your loop stops before the last element.

Should look something like this:

translation_dict = {"": "Null",
                    " ": "Null",
                    "N/A": "Null",
                    "Off": "No",
                    "On": "Yes"}
for counter in range(len(value_list)):
    old_value = str(value_list[counter]).strip('"')
    if old_value in translation_dict:
        value_list[counter] = translation_dict[old_value]
        print counter, value_list[counter]

Upvotes: 1

NPE
NPE

Reputation: 500663

It looks like your strings actually contain double quotes in them. Either remove them from the strings:

while counter < len(value_list)-1:
    value = value_list[counter].strip('"')
    if value in ("", " ", "N/A"):
        ...

or add them to the values you're comparing against:

elif str(value_list[counter]) == '"Off"':
                                 ^^^^^^^ this a string literal containing the
                                         characters ", O, f, f, "

Upvotes: 2

Related Questions