Discuss / Python / 难道list可以越界去空字符串吗?

难道list可以越界去空字符串吗?

Topic source

本地的Yoyo

#1 Created at ... [Delete] [Delete and Lock User]

看到下面的代码可以正常工作,不是很理解。    


    while s[:1] == ' ':

        s = s[1:]

    while s[-1:] == ' ':

        s = s[:-1]

    return s


就是当 s只有一个字符的时候,s[1]越界,为什么 s[1:] 可以取空字符串?哪位大神给解释下。

下标以0开始,所以S[1]代表第二个字母.而S[1:]表示是从第一个字母开始取至最后.

你是微笑

#3 Created at ... [Delete] [Delete and Lock User]

楼上不懂瞎说。

楼主可以试试,假如L = ['Michael', 'Sarah', 'Tracy'],L[3]会报错,但L[3:]就会显示[]


  • 1

Reply