Pages

Saturday, October 27, 2012

functional programming using map with python

Let's say you have a list of strings that ends with '\n' in python.

The simple way to remove '\n' or '\n\r' is string#rstrip() method. You can use readlines() method to read all the contents of file in a string. The problem is all the strings are appended by '\n'.

The issue is how to remove the '\n' for all the elements. From:
['STRING\n',
'\n', 
'STRING\n']
To:
['STRING',
'', 
'STRING']
Using functional programming, you can do it just one line.
lines = map(lambda x: x.rstrip(), lines)

No comments:

Post a Comment