Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Leftmost Characters
|
Posted: Mar 11, 2004 9:01 AM
|
|
If you want to also deal with null, then you'd have to first decide what you want in that case. If s is None (Python's null), then s[:3] will throw a TypeError, since it isn't subscriptable.
In Python, you wouldn't do this in a separate function, since it is so clean and simple. Therefore, I would guess you'd already have enough context to know that s isn't None. For example, if you were reading lines from a file, it might look like this:
for line in file(filename):
firstThree = line[:3]
...
You'd know that you won't get a None result. However, if, for some reason, you really couldn't be sure, you'd just have to first check for None, or catch that exception, whichever style suits your fancy.
By the way, getting a slice from the middle or the end of a collection (or string) in Python outshines Java (and similar languages) even more than getting the first few.
|
|