给定一个数字字符串,按它们出现的顺序输出该字符串中所有长度为 n 的连续子串。
例如,字符串“49142”包含以下 3 位数的序列:
以及以下 4 位数的序列:
如果你从一个 5 位数的字符串里要一个 6 位数的序列,那不管得到什么,都是你自找的。
注意,这些序列只要求在输入中占据_相邻的位置_,数字本身不必_在数值上连续_。
有时需要抛出异常。抛出异常时,一定要附上有意义的错误消息,说明错误的来源。这样代码更易读,也大大有助于调试。如果你确定错误来源属于某种类型,可以选择抛出某种内置错误类型,但同样要附上有意义的消息。
本练习要求:当传入 slice() 函数的序列和(或)长度参数为空或超出范围时,用 raise 语句来“抛出”ValueError。只有既 raise 了 exception,又附带了消息,测试才会通过。
要抛出带消息的 ValueError,把消息写成 exception 类型的实参:
# if the slice length is zero.
raise ValueError("slice length cannot be zero")
# if the slice length is negative.
raise ValueError("slice length cannot be negative")
# if the series provided is empty.
raise ValueError("series cannot be empty")
# if the slice length is longer than the series.
raise ValueError("slice length cannot be greater than series length")