Problem with a dictionary program....
Dan Perl
danperl at rogers.com
Tue Sep 28 16:09:51 EDT 2004
Sorry, my bad. I didn't pay attention and I mistook the join( ) for an
append( ) while just copying and pasting. I've never used join( ) myself so
it didn't click in my mind.
Dan
"Jeff Shannon" <jeff at ccvcorp.com> wrote in message
news:10ljg2vl36tb1e at corp.supernews.com...
> Dan Perl wrote:
>
>>>>output = []
>>>>for character in indput:
>>>> output.append(List[character])
>>>> print ', '.join(output)
>>>>
>>That print statement is actually wrong in many ways. It was probably
>>meant to be something like
>> print ','.join(List[int(character)]) # List[int(character)], not
>> output
>>but even that would start with ',' and it would be on multiple lines
>>(probably not your intention).
>
> No, it wouldn't start with ',' -- you're not parsing that line the same
> way that Python does. ;)
>
> aString.join(aList) will combine a list of strings into a single string,
> using the referenced string as "glue" to stick the pieces together. Thus,
> when the referenced string is ', ', you'll get "item0, item1, item2".
>
> Python will evaluate the call to ', '.join() *before* it prints anything.
> The print statement is given the resulting (single) string as its
> argument. Indeed, that line could be split into several lines for
> clarity:
>
> separator = ', '
> outputstring = separator.join(output)
> print outputstring
>
> The point here is that the for loop builds a list of strings (called
> 'output'). *After* the for loop finishes, then str.join() combines that
> list into a single string, which is printed. However, the O.P. has an
> indentation problem in his code -- he's put the print statement inside his
> for loop, which means that every intermediate stage of the partially-built
> output will get printed as well. All that needs done to fix it is to
> outdent it one level (as Alex suggested).
>
> Your suggestion ("print ','.join(List[int(character)])"), by the way, will
> give results that are far different from what you expect. ;)
>
> >>> List = ['zero', 'one', 'two', 'three']
> >>> print ",".join(List[int('3')])
> t,h,r,e,e
> >>>
>
> You're correctly looking up the word to use for a given digit, but then
> you're passing that single string (rather than a list) to join(), which
> works on any sequence (not just lists). Well, strings are sequences too
> (a sequence of characters), so join() creates a string with each element
> (character) of the sequence separated by the specified string (",").
>
> Jeff Shannon
> Technician/Programmer
> Credit International
>
>
>
>
More information about the Python-list
mailing list