Showing posts with label split and join a string. Show all posts
Showing posts with label split and join a string. Show all posts

Tuesday, November 3, 2015

Showing a List as String in Python

In my previous example and in my website, I have shown you how to split a string and make a list out of it. We simply used the split() function of the string to do so. e.g.

>>> a="The tiny runner running through the narrow edges"
>>> a.split()
['The', 'tiny', 'runner', 'running', 'through', 'the', 'narrow', 'edges']


As you can see the split operation which can split the string and make a list from it. But what if we need to join it again to get the actual string again? Python has a join keyword for this purpose -

>>> ''.join(a)
'The tiny runner running through the narrow edges'


Now, what if we have a list which has integer variables in it. We can not simply right the above function , we need to have a lambda function. Let's have a list of integers - 

>>> a=[1,2,3,4,4,5,5] 
>>> ''.join(a)

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    ''.join(a)
TypeError: sequence item 0: expected string, int found


We can solve the problem using the lambda function, as shown below -


>>> ''.join(map(lambda a:str(a),a))
'123456'


See, the easy way to get the string back!  

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...