Thursday, July 26, 2012

Python: JOIN Function for Iterable

Current post is on how JOIN function works in Python.


Recently started working on Python and got stuck in 'JOIN' function?

Not sure how the JOIN function works?

JOIN Function for iterable in Python:


string str.join(iterable)

where,
          str = string which will be used to append the elements in iterable
          iterable = any iterable in python like list, string

          string = returns the joined string

Confused ??

Reason is we are wired to think like  object.some_function arguments but here its like argument.some_function object(s)


List JOIN in Python:


mypythonlist = ['First', 'Second']
mypytonlist.join('-')   #Incorrect Usage, it will cause AttributeError

'-'.join(mypythonlist)  #Correct Usage

# It will return 'First-Second'


String JOIN in Python:


mypythonstr = 'MyPythonString'
mypythonstr.join('-')  #Incorrect Usage

'-'.join(mypythonstr)   #Correct Usage

# It  will return 'M-y-P-y-t-h-o-n-S-t-r-i-n-g'

I hope now you understand how 'JOIN' function works in Python.


Appreciate your feedback via comments. Thanks.

No comments:

Post a Comment

Disclaimer:

The above post and all the posts in the blog are derived from facts, information, logical interpretation and logical conclusion of printed and internet materials available to me, perceived and produced by 99 gm brain of mine, which by no means always be accurate, consistent and complete.

All the posts are for personal quick reference only.

If any suggestion, correction, misinterpretation, misconception commented, which will be moderated and deleted if required, to avoid unforeseen issues.

If any trademark / copywrite issue is present, do send in a mail and appropriate tag (logo, name, website link) will be attached to the same.

Additional disclaimer will be attached wherever required in the post.