I'm trying to make a fixed length output record, and I'm using a Dictionary as a lookup table to find a code based on the kind of car a person drives.

The routine works fine; I the search the key for the car type, and the value returned is the associated code. Problem is, I need to put that into a list so that I can make the fixed length record later. The field length of the code is 10 bytes, so my plan was..

psudocode:

loop through the csv (spreadheet) to add the key (car model) and value (car code) to a dictionary

assign the value to a variable
answer = CarData[CarType]

L = 10 - len(answer)

list.append(answer + ' ' * L)

The problem is that A) the answer variable holds the 'value', i.e. , not the string representation of '12345' as far as I can tell, and B), the length returned is '1', probably because there is one item, not the length of the item itself.

Is there a way to convert the returned value to a string '12345'? I tried pickle, and that doesn't seem to do it.

>>> l = ['12345'] 
>>> s = ''.join(l)
>>> s
'12345'
>>> len(s)
5
>>> type(l)
<type 'list'>
>>> type(s)
<type 'str'>
>>>

Perfect!, man you guys are good. I see the 'join' statement a lot, I need to read up on it, it seems it has many uses.

simple:

>>> a='Cadillac'
>>> answer=[a]
>>> answer
['Cadillac']
>>> b, = answer
>>> b
'Cadillac'
>>>

b, means singleton tuple, tuple with one element,

value_list =
Here you have a list of one item, you want the item at index zero
value_str = value_list[0]

L = 10 - len(answer)
list.append(answer + ' ' * L)

You can do this if you want but remember that Python has most things built in so you can also use: (look up string formatting)

print "%10s  %10s" % (car, answer)
##
## and your original code should read
print_list = [answer]
for x in range(10-len(answer):
    print_list.append(" ")
##
## which could also be done via
answer += " "*(10-len(answer)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.