1

I am having some trouble finding the solution for the "Join all exercise" in the Hands-on Python Tutorial of Andrew N. Harrington.

Basically, the exercise is to take a list like ['very', 'hot', 'day'] consisting only of strings, and to make one string out of it, in this case 'veryhotday'.

This is the exercise:

'''exercise to complete and test this function'''
def joinStrings(stringList):
    '''Join all the strings in stringList into one string,
    and return the result, NOT printing it. For example:
    >>> s = joinStrings(['very', 'hot', 'day'])
    >>> print(s)  # I can print s OUTSIDE joinStrings
    'veryhotday'
    '''
    # finish the code for this function

def main():
    print(joinStrings(['very', 'hot', 'day']))
    print(joinStrings(['this', 'is', 'it']))
    print(joinStrings(['1', '2', '3', '4', '5']))

main()

So only the first definition may be changed. I solved it like this:

def joinStrings(stringList):
    return ''.join(stringList)

and I believe this works and is correct. Correct me if I am wrong here, but the problem is that it has to be solved differently. I have to sort of accumulate the different strings. just as they show here with integers:

def sumList(nums):
    ’’’Return the sum of the numbers in the list nums.’’’
    sum = 0
    for num in nums:
        sum = sum + num
    return sum

and really I just can't figure it out, so please help me!

Gareth Rees
  • 64,967
  • 9
  • 133
  • 163
user1666419
  • 77
  • 1
  • 6

2 Answers2

2

''.join(stringList) is the correct way. What is the problem?

If it has to be done differently, you could do one of:

import operator
return reduce(operator.add, stringList)

or even

s = ''
for string in stringList:
    s = s + string
return s

but that's unnecessary complication, since using join like you suggested is the simplest and preferred way. Probably also the fastest.

Kos
  • 70,399
  • 25
  • 169
  • 233
  • that second suggestion is perfect! exactly what i was looking for. thx – user1666419 Sep 12 '12 at 16:45
  • 1
    Are you sure you can use sum like this, I get a TypeError: `sum() takes no keyword arguments`... ? Looking at [docs](http://docs.python.org/library/functions.html#sum), start can't be a string! – Andy Hayden Sep 12 '12 at 16:49
  • @hayden right, I didn't know that sum has a special case for strings (a bit surprising but reasonable since `join` is the way to go anyway) – Kos Sep 12 '12 at 16:55
  • reducing by operator.add is _MUCH_ slower than ''.join ... orders of magnitude... see http://stackoverflow.com/a/3525380/541038 – Joran Beasley Sep 12 '12 at 16:58
2

Have a look at the str.join() method

''.join(['a','b','c']) # 'abc'
' '.join(['a','b','c']) # 'a b c'
print ' are '.join(['how', 'you']) # > how are you
s = ''.join(['%d'%i for i in range(10)]) # 01234567789

The str.join() function does not print anything, it simply creates a new string from a list of strings.

Nisan.H
  • 6,032
  • 2
  • 26
  • 26