Question

The values in the arrays are fine. If I print them out separately in a loop they come out as they should, but the moment I put them all together it doesn't print the first two values and jumbles the rest. Here's the print snippet:

print '['
for i in range(1, x):
    print '{\"' + fNames[0] + '\":"' + fNames[i] + '\", \"' + lNames[0] + '\":\"' + lNames[i] + '\", \"' + descs[0] + '\":\"' + descs[i] + '\"},\r'
print ']'

Here's what it outputs:

[
"},A really cool guy, "lname":"Bishop", "description
"},A really cool galname":"Patzer", "description
"},A really cool momlname":"Robertson", "description
"},A really cool dadame":"Bishop", "description
"},A really cool doglname":"Bishop", "description
"},A really cool cat"lname":"Jack", "description
]

Notice that it doesn't output fName[0] and fName[i].

If I comment out the end of the print statement like so:

print '['
for i in range(1, x):
    print '{\"' + fNames[0] + '\":"' + fNames[i] + '\", \"' + lNames[0] + '\":\"' + lNames[i] + '\", \"' + descs[0] + '\":\"' #+ descs[i] + '\"},'
print ']'

It prints out most of it correctly, besides the 'f' in "fname" and notice that it doesn't print out the last '\":\"' at all either. I've already ran the arrays through the filter() function to strip newlines, and made sure my regex doesn't pick them up. This is how I fill the arrays:

with open(file, "rb") as fin:
    for line in fin:
        col1Reg = re.search('^(.+?)(?=,)', line)
        fNames.append(col1Reg.group(0))

        col2Parsed = '(?<=' + fNames[x] + ',)(.*)(?=,)'
        col2Reg = re.search(col2Parsed, line)
        lNames.append(col2Reg.group(0))

        col3Parsed = '(?<=' + lNames[x] + ',)(.*)(?=\n)'
        col3Reg = re.search(col3Parsed, line)
        descs.append(col3Reg.group(0))

        x += 1

What the heck is going on? Everything in the arrays is correct and in the correct position, so why is this happening?

Was it helpful?

Solution

It looks like you are trying to output json. Instead of building a string, why not create a list of dictionaries and dump it to json via something like this:

import json
list1 = []
for x in range(i):
  list1.append({
     'name': 'value',
  })
print json.dumps(list1, indent=4)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top