Jump to content

Replicating .join with For loop in Python

- - - - -

  • Please log in to reply
1 reply to this topic

#1
MyNewAccount48

MyNewAccount48

    Newbie

  • Members
  • Pip
  • 1 posts
I'm attempting to come up with a function that will use a for loop to replicate the .join function. For example, L = [this, is, a, list], function(L, "/"), it would return a string "this/is/a/list". I'm stuck and can't seem to figure out how to add the elements from the list and then turn it into a string. Any advice would be appreciated.

#2
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
What part are you having difficulty with? I'll provide you with a possible answer, but I hope that you with to learn.

L = [3, 'little', 'pigs', 'murdered', 19, 'orphans']


def using_for(iterable, seperator=' '):
    t = ''
    for i in iterable[:-1]:
        t += '%s%s' % (i, seperator)
    return t + iterable[-1].__str__()


print using_for(L, '/')





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users