1

First of all, I would like to apologize for my english since it is not my native language.

I'm having a quite crazy problem with the following code:

linecounter = []

for i in range(20):
    linecounter.append("Color "+str(i)+"\n")


for line in linecounter:
    color_list = range(20)
    for j in range(len(color_list)):
        stri = "Color " + str(j+1)
        if stri in line:
            print j

The result I expect: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

The result I'm getting: 0 1 2 3 4 5 6 7 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 0 18

Can somebody tell me how I get this result or how I get the result I want?

I would like to thank everyone who answers.

Sincerely, Nikster

2 Answers 2

1

Those extra zeroes are being printed because of the way the in operator works for strings. When line is "Color10" and stri is "Color1", then if stri in line evaluates to True, and prints the value of j, which is zero at the time.

Try using an equality comparison instead of in. You would also need to add a newline to the end of stri so that they compare properly.

    stri = "Color " + str(j+1) + "\n"
    if stri == line:
        print j

This will print the numbers from 0 through 18. I don't entirely understand what you're trying to do, but if you want 19 to get printed, you could try not adding 1 to j:

    stri = "Color " + str(j) + "\n"
    if stri == line:
        print j
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, I could solve my problem with a variation of your answer
0

Strange logic but:

linecounter = []

for i in range(20):
    linecounter.append("Color "+str(i))


for line in linecounter:
    color_list = range(20)
    for j in range(len(color_list)):
        stri = "Color " + str(j+1)
        if stri == line:
            print j

2 Comments

Thanks for the answer, but it only solves the problem of this example. In my main program, I read the lines from a text file, so this doesn't realy helps me.
Just add new line'\n' linecounter.append("Color "+str(i)+"\n") stri = "Color " + str(j+1)+"\n"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.