python range()函数的用法

在以往用range函数的时候从未深入的了解过,只是简单的这样用,而从未去想其他的

>>> range(1,5) #两个参数的,从1到5
[1, 2, 3, 4]
>>> range(1,5,2) #三个参数的,从1到5,间隔数字为2,所以显示奇数
[1, 3]
>>> range(5) #一个参数的,默认start是从0开始,end是5
[0, 1, 2, 3, 4]

今天看《python核心编程》第二版中,在讲切片时,作者举了一个例子:“有这么一个问题:有一个字符串,我们想通过一个循环按照这样的形式显示它:每次都把位于最后的一个字符砍掉”,这个例子虽然很小,也很简单

但是也让我对range函数有了新的认识,看来以前还是书读的不仔细,太浮躁了
书中代码:
 

>>> s=’abcde’
>>> i=-1
>>> for i in range(-1,-len(s),-1):
… print s[:i]

abcd
abc
ab
a

 
但是程序存在的问题就是无法在第一次迭代的时候显示整个字符串,而作者给出的解答方式是:
 
用None作为索引值

>>> s="abcde"
>>> for i in [None] + range(-1,-len(s),-1):
… print s[:i]

abcde
abcd
abc
ab
a

 
由此可以看出用0作为迭代的第一项是不可行的,因为切片s[:0]将会返回空字符串,如果是s[0:]这样的话迭代的第一项没有问题,但是迭代从第二项便开始出错,这也不符合题目的要求

>>> s[:0]

>>> s[0:]
‘abcde’
>>> s[1:]
‘bcde’

 
因此要用正值作为迭代项的话,第一项必须为len(s),这就要对range的用法做出相应的修改
 

>>> s="abcde"
>>> for i in range(len(s),0,-1):
…     print s[:i]
…     
abcde
abcd
abc
ab
a

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. Python 多线程 XML RPC的实现

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu