开发者

Python - skip outofbounds exceptions for the sake of clarity?

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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜