Suppose you have to accom开发者_如何学编程plish this quite generic task:
Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.
Now, as Python lists silently skip out of bounds exceptions, one solution could be:
def front(string):
return 3 * string[:3]
This works even if the given string's length is less than length 3. But is this good practice?
Yes, it is perfectly a good practice, if your requirement is exactly that. :)
return 3 * string[:3]
精彩评论