#!/usr/bin/python
# 1.11. Naming a Slice
# Problem: Your program has become an unreadable mess of
# hardcoded slice indices and you want to clean it up.
###### 0123456789012345678901234567890123456789012345678901234567890'
record = '....................100 .......513.25 ..........'
cost = int(record[20:32]) * float(record[40:48])
print (cost)
# name the slices
SHARES = slice(20,32)
PRICE = slice(40,48)
cost = int(record[SHARES]) * float(record[PRICE])
print (cost)
items = [0, 1, 2, 3, 4, 5, 6]
a = slice(2, 4)
print (items[2:4])
print (items[a])
items[a] = [10,11]
print (items)
del items[a]
print (items)
a = slice(10, 50, 2)
print (a.start, a.stop, a.step)
s = 'HelloWorld'
indice = a.indices(len(s))
print (indice)
for i in range(*a.indices(len(s))):
print(s[i])
这是Python Cookbook第1.11章中的示例。
print (indices)
这应该会给我(5,10,2)
,但它会给我(10,10,2)
。然后以下for循环没有打印任何东西。
为什么我的代码显示的结果与书中的结果不同?
答案 0 :(得分:2)
这实际上是书中的一个错误。如果您查看errata并向下滚动到第19页,则会出现以下说明:
此示例“a.indices(len(s))”导致输出与书中打印的输出不同,假设切片a是切片a,如上例中所示。如果是切片(5,50,2)左右,它将以所示的方式工作。或者我错了吗?
作者或编辑的注意事项: 将中间页面的示例更改为:
>>> a = slice(5, 50, 2) >>> a.start 5 >>> a.stop 50 >>> a.step 2 >>>
然后底部的问题示例应该有效。