Newbie help understanding...

Amit Khemka khemkaamit at gmail.com
Sat May 26 03:43:13 EDT 2007


On 26 May 2007 00:23:32 -0700, mark <j25bravo at gmail.com> wrote:
> Hi I am trying to get a piece of code to work based on an exercise in
> a book. Any help appreciated. Can someone please explain what is going
> on here.
>
> I am trying to read from a text file a list of cards with the
> following format and sort firstly by suit and then by rank
>
> h 1
> d 2
> c 5
> s 9
> h2
> d3
>
> etc...
>
> I get the following error;
> Traceback (most recent call last):
>   File "F:/###UNI###/ITC106/ass2/cardread.py", line 25, in <module>
>     t.append( t[0] + 400 )
> AttributeError: 'str' object has no attribute 'append'

> def read_cards(filename):
>     cards = []
>     for card in open(filename, 'r'):
>         cards.append(card.strip())
>     return cards
>
> # read the deck of cards from a file
> filename = 'cards.txt'
> cards = read_cards(filename)
>
>
> for t in read_cards(filename):
>     if t[1] == 'h':
>         t.append( t[0] + 100 )
>     elif t[1] == 'd':
>         t.append( t[0] + 200 )
>     elif t[1] == 'c':
>         t.append( t[0] + 300 )
>     else:
>         t.append( t[0] + 400 )

 In read_cards function you are appending  a string in the  list
'cards' , where i guess you wanted to append a list of suit and rank
in list cards.

def read_cards(filename):
    cards = []
    for card in file(filename):
       cards.append(cards.split()) # i assume that suit and rank is
separated by white space
    return cards

or better still

cards = [card.split() for card in file(filename)]

Cheers,

----
Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.



More information about the Python-list mailing list