简体   繁体   中英

Python for loop using range results in the index being printed rather than the value

I'm looping over the below output from a difflib compare of two configuration files:-

[server]
+ # web-host-name = www.myhost.com
+ https-port = 1080
+ network-interface = 0.0.0.0
[process-root-filter]
[validate-headers]
[interfaces]
[header-names]
[oauth]
[tfim-cluster:oauth-cluster]
[session]
+ preserve-inactivity-timeout = 330
[session-http-headers]

what I'm trying to achieve is to parse the diff and only print out headers (items in []) for which the next item in the list starts with +

I have the following code that is running without errors.

for x in range(0, (len(diff) - 1)):
        print str(x)  #prints index number instead of the content of the line
        z = str(diff)[x+1]
        if str(x).startswith('+'):
            print(x) # prints nothing x contains the index of the line instead of the text
        elif str(x).startswith('  [') and z.startswith('+'):
            print(x)

The problem is that the index number of the line is being returned in the loop rather than the text in the line.

eg print output from

[0]
[1]
[2]
[3]
[4]

I know I must be missing something basic here but can't seem to find the answer after.

What you are doing is looping through an x of the range 0 to length of diff - 1. This will provide you with all integer values between those two integers, eg

    for x in range(0, 3):
        print(str(x) + ' ')

will give you back:

0 1 2 3

So if diff is a list of strings for each new line, to get the line, you can just use :

    # iterate through list diff
    for x in diff:
        print(x)

to print out all of your lines. If you now want to know if its a header before you print it out:

    # iterate through list diff
    for x in diff:
        # test if x is a header
        if x.startswith('[') and x.endswith(']'):
            print(x)

Please note that none of this code has been tested.

Hope this helps

EDIT: if diff is not a list of lines but rather one single string, you can use

    line_list = diff.split('\n')

to get a list of lines.

EDIT 2: If you now want to also check the next line within the first iteration, we have to use indexes instead:

    # for every index in list diff
    for i in range(0, len(diff) - 1):
        if diff[i].startswith('[') and diff[i + 1].startswith('+'):
            # do something if its a header with following content
        elif diff[i].startswith('+'):
            # do something if the line is data
for x in range(0, (len(diff) - 1)):
    print str(x)  #prints index number instead of the content of the line

The reason the index is being printed here is because x is not iterating over the contents of diff, it's iterating over an integer range that is equal to the length of diff. You already have the answer as to why your print is giving the index instead of the string content here, on the very next line: z = str(diff)[x+1] Calling diff[x] refers to the line of diff at index x, so if you want to print diff's content or refer to it in later lines you need to do the same thing: print str(diff[x])

thanks to both @pheonix and @rdowell comments above. I've updated the code to the below which now works:-

for i in range(0, len(diff) - 1):
    if diff[i].startswith('  [') and diff[i + 1].startswith('+'):
            # do something if its a header with following content
        print str(diff[i])
    elif diff[i].startswith('+'):
            # do something if the line is data
        print str(diff[i])

This post will be something I'll refer back to as I'm just getting to know what you can and can't do with the different object types in Python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM