[Tutor] yet another misunderstanding on my part

Alan Gauld alan.gauld at btinternet.com
Wed Oct 22 12:11:04 CEST 2014


On 22/10/14 05:54, Clayton Kirkwood wrote:
> __author__ = 'SYSTEM'

Its best not to invent your own dunder names.
You might run into a problem if a future Python release
decided to use the same name under the covers.

> import string

Do you need this? Its very unusual these days
to use the string module.

> #Pricing                Dividends
> raw_table = ('''
> a: Ask    y: Dividend Yield
> b: Bid     d: Dividend per Share
> b2: Ask (Realtime)           r1: Dividend Pay Date
> b3: Bid (Realtime)            q: Ex-Dividend Date
> p: Previous Close
> o: Open

Seems to be missing a closing '''') ?

BTW the above would be a great place to use a dictionary,
its already almost in the right format...

> import re, string

Keep imports together, it would make it easier to
see the duplication of string...

> col_position, code, description = 0, [], []
> key_name = raw_table.replace('\t','\n')
>
> for each_line in  key_name.splitlines():
>      if ':' in each_line:
>         code[col_position], description.append()  =
> each_line.split(‘:’)           #neither works; first one is out of range

Where did 'code' come from?
You are trying to index into a non existent variable.
You need to declare the list and then use it.
The usual way to add items to a list is to use
the append() method.


>          code[col_position] =  each_line.split(':')        #why doesn’t

Again code is still undeclared.

> code.append(c)

And even this won't work until you declare code to be a list.

> I’ve seen an example of description.strip() work from a for in loop
> assignment with out the can’t assign to function.

I can't quite parse that but I think you are looking at the wrong 
problem. Its not the strip() thats causing problems its the use
of code before declaring it.

code = []   # or code = list()  each declares code to be an empty list
code.append(item)   # this now adds an item to the list

If you want to use indexing to assign values then you need to assign 
dummy values to create the 'spaces' first. This is often done using a 
list comprehension:

# create a list of length size each containing zero
code = [0 for n in range(size)]

or cell multiplication

code = [0] * size


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list