[Tutor] Joining all strings in stringList into one string

Dave Angel d at davea.name
Wed May 30 19:03:44 CEST 2012


On 05/30/2012 12:21 PM, Akeria Timothy wrote:
> Hello all,
>
> I am working on learning Python(on my own) and ran into an exercise that I
> figured out but I wanted to know if there was a different way to write the
> code? I know he wanted a different answer for the body because we haven't
> gotten to the ' '.join() command yet.
>
> This is what I have:
>
> def joinStrings(stringList):
>  string = []
>     for string in stringList:
>         print ''.join(stringList)
>
>
> def main():
>     print joinStrings(['very', 'hot', 'day'])
>     print joinStrings(['this', 'is', 'it'])
>     print joinStrings(['1', '2', '3', '4', '5'])
>
> main()
>
>
> thanks all
>
>

I'm not sure what you want us to do here.  You don't quote the
"exercise" description, so about all I can do is point out the bugs and
inefficiencies in the code.

Your indentation won't work.  You have string =  indented by one column,
and the for loop indented by 3 more.  Those two lines have to start in
the same column.  Of course, if you had run it that way, the compiler
would have told you that.  So presumably you've retyped it into this
message, which is very bad practice.   Use copy/paste.

  File "timothy.py", line 3
    for string in stringList:
    ^
IndentationError: unexpected indent

Fixing that.  Next problem is that main() uses the results of
joinStrings(), but there is no return statement in joinStrings().  So it
prints None.  Presumably you meant to have joinStrings() return its
result, INSTEAD of printing it.

Next, in joinStrings(), you start by initializing string=.  But then you
immediately overwrite that value with the for loop, so it was wasted. 
Presumably you wanted to use two different names there, and do something
to the first variable each time through the loop.

Next, in the loop, you do the same work multiple times, never using the
individual value of  string.


So, please tell us the actual assignment, and we can help you get
there.  There is certainly a way to have joinStrings() do the equivalent
of "".join(), but it wouldn't look much like what you've written.

Usually, the practice of making a docstring for each function can help
you get the purpose straight in your mind.  What does the function
expect as argument(s), and what will it do, and what will it return? 
And what side effects does it have, like printing ?  Usually, a function
either does some work, or it displays some results.  Doing both is a
sign of a program that's still being debugged.


-- 

DaveA



More information about the Tutor mailing list