poython 不知哪里出错了?

sayigood 2010-01-19 11:31:40
代码及提示如下:
>>> s
'asdfadsf'
>>> for i in [None] + range(-1, -len(s), -1):
... print (s[:i])
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "range") to list

非常感谢你的帮助。。。
...全文
227 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
sayigood 2010-01-20
  • 打赏
  • 举报
回复
Get it!
谢谢各位
sayigood 2010-01-19
  • 打赏
  • 举报
回复
这段代码是python核心编程中的一段:
用以实现将字符串s每次显示都把最后一个字符去掉
不知道该如何修改啊?谢谢
Semigod 2010-01-19
  • 打赏
  • 举报
回复
range得到的结果并不是list,这一点你没有搞清楚
range()只是iterable object,并不是list
goosman 2010-01-19
  • 打赏
  • 举报
回复
The range type is an immutable sequence which is commonly used for looping. The advantage of the range
type is that an range object will always take the same amount of memory, no matter the size of the range it
represents. There are no consistent performance advantages.
Range objects have very little behavior: they only support indexing, iteration, and the len() function.

上面是3.1的library文档中对新的range类型的描述.
其仅支持索引, 迭代, len()几种有限的操作.
goosman 2010-01-19
  • 打赏
  • 举报
回复
python 3之后, range返回的是range对象了.
在此之前的版本中, 楼主的代码执行是没有问题的.
ermine 2010-01-19
  • 打赏
  • 举报
回复
点错键了。。。。
python3.0里,可以用list将range转换。
>>> for i in [None]+list(range(-1,-len(s),-1)):
print(s[:i])


asdfadsf
asdfads
asdfad
asdfa
asdf
asd
as
a
ermine 2010-01-19
  • 打赏
  • 举报
回复
Python3.0
>>> for i in [None]+range(-1,-len(s),-1):
print(s[:i])
dskit 2010-01-19
  • 打赏
  • 举报
回复
成功输出:
asdfadsf
asdfads
asdfad
asdfa
asdf
asd
as
a
dskit 2010-01-19
  • 打赏
  • 举报
回复


s = 'asdfadsf'
for i in [None] + range(-1, -len(s), -1):
print s[:i]


在python2.6下没有任何问题。

37,742

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧