[Tutor] Joining all strings in stringList into one string

Dave Angel d at davea.name
Wed May 30 21:43:58 CEST 2012


A procedural point here:   You forgot to include the list, and just
replied to me privately.  Normally, what you should do is a Reply-All.
Or else make sure  tutor at python.org  is one of the To: or CC: list



On 05/30/2012 01:40 PM, Akeria Timothy wrote:
> I did copy and paste and I'm learning Python on my own using Hands-on Pyton
> Tutorial and this was one of the exercises. He gave us the  everything but
> the body. So this is what I started out with:
> 
> def joinStrings(stringList):
>     '''Join all the strings in stringList into one string,
>     and return the result. For example:
>     >>> print joinStrings(['very', 'hot', 'day'])
>     'veryhotday'
>     '''
>     # finish the code for this function

Very good.  Why did you remove that docstring from your own code before
posting it?

> 
> 
> def main():
>     print joinStrings(['very', 'hot', 'day'])
>     print joinStrings(['this', 'is', 'it'])
>     print joinStrings(['1', '2', '3', '4', '5'])
> 
> main()
> 
>    <SNIP>
> 
> I know it's wrong but it worked so that's why I'm asking for the proper way
> to do it.

The output I got from your code (after fixing the indent) was


davea at think:~/temppython$ python timothy.py
veryhotday
veryhotday
veryhotday
None
thisisit
thisisit
thisisit
None
12345
12345
12345
12345
12345
None

and what I think the instructor expected was:

veryhotday
thisisit
12345

Similar, but not the same.

First, the function is NOT supposed to print anything.  According to the
docstring, the function returns the result, not prints it.

So you could come up with:

def joinStrings(stringList):
    '''Join all the strings in stringList into one string,
    and return the result. For example:
    >>> print joinStrings(['very', 'hot', 'day'])
    'veryhotday'
    '''
    # finish the code for this function
    return "".join(stringList)


But as you said in your original message, he presumably hasn't
introduced that join method yet, so you would like to do it by hand.
Very good way to learn.

You had the right concept, of having an 'accumulator" to gather the
parts of the result together.  However, you are not trying to return a
list, you're trying to return a string.  So the accumulator must be an
empty string.  I'll give it a different name, so it doesn't conflict
with the loop variable.
    res = ""
    for string in stringList:
        something here that modifies res

    return res

Your challenge is now to supply the line in the middle.

-- 

DaveA


More information about the Tutor mailing list