我已经阅读了一段这样的代码:
s = self.buffer_file.readline()
if s[-1:] == "\n":
return s
Run Code Online (Sandbox Code Playgroud)
如果我这样做:
s = 'abc'
In [78]: id(s[-1:]), id(s[-1])
Out[78]: (140419827715248, 140419827715248)
In [79]: id(s[-1:]) is id(s[-1])
Out[79]: False
In [80]: id(s[-1:]) == id(s[-1])
Out[80]: True
Run Code Online (Sandbox Code Playgroud)
这对我来说没有意义,ID号是相同的,但ID是不同的.所以他们因某种原因不同.
区别在于切片列表的结果是列表
x = [1, 2, 3]
print(x[-1]) # --> 3
print(x[-1:]) # --> [3]
Run Code Online (Sandbox Code Playgroud)
第二种情况恰好是一个元素的列表,但它仍然是一个列表.
但请注意,Python没有与char类型不同的str类型,这意味着str对象的元素访问和切片都返回另一个str对象:
print("abcd"[-1]) # --> "d"
print("abcd"[-1:]) # --> "d"
Run Code Online (Sandbox Code Playgroud)
例如使用的唯一的优点s[-1:]或s[:1]用细绳代替s[-1],并s[0]是切片表情不会引发作用于一个空字符串时,运行时错误(一些元素访问一样)......这可能允许代码简化:
if len(s) > 0 and s[0] == '*': ...
if s[:1] == '*': ...
Run Code Online (Sandbox Code Playgroud)
关键的实际好处,s[-1:]而不是s[-1]前者将产生一个空的迭代,而不是停止跟踪.
>>> 'hi'[-1:]
'i'
>>> 'hi'[-1]
'i'
>>> ''[-1:]
''
>>> ''[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)
这允许通过简单地评估而不是生成需要用结构处理的错误if s[-1:] == "\n":来处理空行s而不用它前面.if s:Falsetry..except
这id(s[-1:]) is id(s[-1])意味着id本身(整数)是引用相等的.假设CPython 2.
这个问题可能是指定的实现.
注意小整数池.http://davejingtian.org/2014/12/11/python-internals-integer-object-pool-pyintobject/.
这可能有所帮助:
Python 2.7.10 (default, Sep 23 2015, 04:34:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
>>> s = 'abc'
>>> s[-1:]
'c'
>>> s[-1]
'c'
>>> s[-1:]
'c'
>>> a = s[-1:]
>>> b = s[-1]
>>> id(a)
4531751912
>>> id(b)
4531751912
>>> a is b
True
>>> id(a) is id(b)
False
Run Code Online (Sandbox Code Playgroud)
的对象a和b是相同的对象,但其id有两个ints不属于"参考相等".
有关整数的更多信息:
>>> 5 is 100
False
>>> 5 is 5
True
>>> 10000 is 10000
True
>>> 1000000000 is 1000000000
True
>>> a = 10000000
>>> a is 10000000
False
>>> a, b = 100000000, 100000000
>>> a is b
True
>>> a is 100000000
False
>>> id(100000000)
140715808080880
>>> id(a)
140715808080664
>>> id(b)
140715808080664
>>> id(100000000)
140715808080640
>>>
Run Code Online (Sandbox Code Playgroud)
进一步阅读:PyPy实现的详细信息:http://doc.pypy.org/en/latest/cpython_differences.html#object-identity-of-primitive-values-is-and-id