Sometimes it's the little things that make my day. For example, string handling and tuple unpacking.
It's so easy to work with strings in Python! Here is the code to drop the last character from a string:
s = s[:-1]
In Java that becomes
s = s.substring(0, s.length()-1);
How about splitting a string on the last instance of '/', where at least one / is assumed to be present?
i = s.rindex('/')
prefix = s[:i]
lastElement = s[i+1:]
In Java it is about the same, though much more verbose:
int i = s.lastIndexOf('/');
String prefix = s.substring(0, i);
String lastElement = s.substring(i+1);
In Python, I can easily make this into a function that returns both prefix and lastElement. With tuple-unpacking, the client code can assign the values to two varibles:
def splitPath(path):
i = path.rindex('/')
return path[:i], path[i+1:]
prefix, last = splitPath(aPath)
There is no reasonable equivalent in Java.
I am working on a small database application. It has a utility class that queries the database, returning the result as a list of lists, one for each row. Client code can easily unpack the row lists into individial variables. This is what it looks like:
data = self.dba.queryAsList('select topicid, parentid, groupid from topic')
for topicid, parentid, groupid in data:
Sweet!
Update: A couple of comments point out that the best way to split a file path in Python is to use os.path.split(). I agree! But the point of the post is to show how easy it is to work with strings; maybe I'll talk about the standard libraries another time.
|