奇怪的 Python 特性

2017-09-01 14:50:58 +08:00
 eloah

好吧,是一个 feature 还是 bug 已经搞不清了

Ubuntu 16.04.03 Python3.5.2

>>> a = ''
>>> a[1:-1]
''
>>> a[2:-1]
''
>>> a[3:-1]
''

2838 次点击
所在节点    Python
13 条回复
clino
2017-09-01 14:52:03 +08:00
你觉得应该返回什么?
eloah
2017-09-01 14:54:57 +08:00
@clino
raise IndexError
013231
2017-09-01 15:12:06 +08:00
是 feature。
https://docs.python.org/3.6/library/stdtypes.html#common-sequence-operations

s[i:j:k]
“ The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.”
est
2017-09-01 15:17:23 +08:00
In [457]: a='a'

In [458]: a[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]
Out[458]: 'a'
mark06
2017-09-01 15:18:25 +08:00
> However, out of range slice indexes are handled gracefully when used for slicing:

```
>>> word[4:42]
'on'
>>> word[42:]
''
```
[document]( https://docs.python.org/3.5/tutorial/introduction.html#strings)
SuperMild
2017-09-01 15:36:11 +08:00
动态语言一般倾向于默认一种行为以方便使用,而不是抛出异常,抛出异常还要处理异常多麻烦啊。动不动就抛出异常那是静态语言的习惯。
LeeSeoung
2017-09-01 15:42:44 +08:00
说实话,要是避免抛异常你是不是还要多写几个判断边界的语句,但是写完判断边界后你觉得是这种特性好用,还是你自己再写一堆代码好用。。
eloah
2017-09-01 15:50:45 +08:00
@est
这个死循环反而很好理解啊
eloah
2017-09-01 15:54:30 +08:00
@SuperMild
@LeeSeoung
可以理解的,写代码起来方便
但是不抛异常可能会导致错误被隐藏起来啊
clino
2017-09-01 16:00:50 +08:00
@eloah 判断返回值是否空不就行了?
winglight2016
2017-09-01 20:47:44 +08:00
@eloah 这大概是语言背后的哲学不同,我习惯 java 就很难理解这种 feature
jedihy
2017-09-02 07:36:11 +08:00
一直都是这样啊
popbones
2017-09-02 10:16:00 +08:00
异常不一定带表错误,是否检查以及如何处理异常是程序逻辑,程序员需要根据需要使用相应的语法功能。

这就好比什么时候用 if a 什么时候用 if a is not None 是程序员的责任而不是语言的责任一样。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/387458

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX