推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
eloah
V2EX  ›  Python

奇怪的 Python 特性

  •  1
     
  •   eloah · Sep 1, 2017 · 3675 views
    This topic created in 3354 days ago, the information mentioned may be changed or developed.

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

    Ubuntu 16.04.03 Python3.5.2

    >>> a = ''
    >>> a[1:-1]
    ''
    >>> a[2:-1]
    ''
    >>> a[3:-1]
    ''
    
    
    13 replies  •  2017-09-02 10:16:00 +08:00
    clino
    clino
    Sep 1, 2017
    1
    你觉得应该返回什么?
    eloah
    eloah
    OP
    Sep 1, 2017
    2
    @clino
    raise IndexError
    013231
    013231
    Sep 1, 2017
    3
    是 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
    est
    Sep 1, 2017
    4
    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
    mark06
    Sep 1, 2017
    5
    > 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
    SuperMild
    Sep 1, 2017
    6
    动态语言一般倾向于默认一种行为以方便使用,而不是抛出异常,抛出异常还要处理异常多麻烦啊。动不动就抛出异常那是静态语言的习惯。
    LeeSeoung
    LeeSeoung
    Sep 1, 2017
    7
    说实话,要是避免抛异常你是不是还要多写几个判断边界的语句,但是写完判断边界后你觉得是这种特性好用,还是你自己再写一堆代码好用。。
    eloah
    eloah
    OP
    Sep 1, 2017
    8
    @est
    这个死循环反而很好理解啊
    eloah
    eloah
    OP
    Sep 1, 2017
    9
    @SuperMild
    @LeeSeoung
    可以理解的,写代码起来方便
    但是不抛异常可能会导致错误被隐藏起来啊
    clino
    clino
    Sep 1, 2017
    10
    @eloah 判断返回值是否空不就行了?
    winglight2016
    winglight2016
    Sep 1, 2017
    11
    @eloah 这大概是语言背后的哲学不同,我习惯 java 就很难理解这种 feature
    jedihy
    jedihy
    Sep 2, 2017
    12
    一直都是这样啊
    popbones
    popbones
    Sep 2, 2017
    13
    异常不一定带表错误,是否检查以及如何处理异常是程序逻辑,程序员需要根据需要使用相应的语法功能。

    这就好比什么时候用 if a 什么时候用 if a is not None 是程序员的责任而不是语言的责任一样。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   695 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 20:53 · PVG 04:53 · LAX 12:53 · JFK 15:53
    ♥ Do have faith in what you're doing.