Python学习--字符串slicing

Found this great table at http://wiki.python.org/moin/MovingToPythonFromOtherLanguages

Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.

Index from rear:    -6  -5  -4  -3  -2  -1      a=[0,1,2,3,4,5]    a[1:]==[1,2,3,4,5]
Index from front:    0   1   2   3   4   5      len(a)==6          a[:5]==[0,1,2,3,4]
                   +---+---+---+---+---+---+    a[0]==0            a[:-2]==[0,1,2,3]
                   | a | b | c | d | e | f |    a[5]==5            a[1:2]==[1]
                   +---+---+---+---+---+---+    a[-1]==5           a[1:-1]==[1,2,3,4]
Slice from front:  :   1   2   3   4   5   :    a[-2]==4
Slice from rear:   :  -5  -4  -3  -2  -1   :
                                                b=a[:]
                                                b==[0,1,2,3,4,5] (shallow copy of a)

In python 2.7

Slicing in python

[a:b:c]

len = length of string, tuple or list

c -- default is +1. sign of c indicates forward or backward, absolute value of c indicates steps. Default is forward with step size 1. Positive means forward, negative means backward.

a -- when c is positive or blank, default is 0. when c is negative, default is -1.

b -- when c is positive or blank, default is len. when c is negative, default is -(len+1).

Understanding index assignment is very important.

In forward direction, starts at 0 and ends at len-1

In backward direction, starts at -1 and ends at -len

when you say [a:b:c] you are saying depending on sign of c (forward or backward), start at a and end at b ( excluding element at bth index). Use the indexing rule above and remember you will only find elements in this range

-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1

but this range continues in both directions infinitely

...,-len -2 ,-len-1,-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1, len, len +1, len+2 , ....

e.g.

             0    1    2   3    4   5   6   7   8   9   10   11
             a    s    t   r    i   n   g
    -9  -8  -7   -6   -5  -4   -3  -2  -1

if your choice of a , b and c allows overlap with the range above as you traverse using rules for a,b,c above you will either get a list with elements (touched during traversal) or you will get an empty list.

One last thing: if a and b are equal , then also you get an empty list

>>> l1
[2, 3, 4]

>>> l1[:]
[2, 3, 4]

>>> l1[::-1] # a default is -1 , b default is -(len+1)
[4, 3, 2]

>>> l1[:-4:-1] # a default is -1
[4, 3, 2]

>>> l1[:-3:-1] # a default is -1
[4, 3]

>>> l1[::] # c default is +1, so a default is 0, b default is len
[2, 3, 4]

>>> l1[::-1] # c is -1 , so a default is -1 and b default is -(len+1)
[4, 3, 2]

>>> l1[-100:-200:-1] # interesting
[]

>>> l1[-1:-200:-1] # interesting
[4, 3, 2]

>>> l1[-1:5:1]
[4]

>>> l1[-1:-1:1]
[]

>>> l1[-1:5:1] # interesting
[4]

>>> l1[1:-7:1]
[]

>>> l1[1:-7:-1] # interesting
[3, 2]


时间: 2024-08-28 12:44:19

Python学习--字符串slicing的相关文章

python学习---字符串

单引号,双引号,三引号,原型字符串几种形式 1.创建字符串:单引号,双引号,str()几种创建方式 2.访问子串:切片方式 3.修改或者说更新字符串:“+”运算,给字符串内容增加一个长度的字符串:重新赋值方式: 4.删除子串:切片做“+”运算(aString = aString[:3] + aString[4:]),del语句删除字符串,或者给字符串赋值空(“”) 5.对字符串应用成员操作符in或者 not in 返回True 或者False 6.编译时字符串连接,上面的语法在运行时字符串连接的

Python学习-字符串格式化

Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存. 1.百分号方式 格式化字符串时,Python使用一个字符串作为模板.模板中有格式符,这些格式符为真实值预留位置,并说明真实数值应该呈现的格式.Python用一个tuple将多个值传递给模板,每个值对应一个格式符. 比如下面的例子: print("I'm %s. I'm %d year old" % ('Vamei',

Python学习—字符串练习

Python字符串练习 输入一行字符,统计其中有多少个单词,每两个单词之间以空格隔开.如输入: This is a c++ program. 输出:There are 5 words in the line. [考核知识点:字符串操作]代码: s=input("请输入一行句子:") list = s.split(' ') print("There are %d words in the line." %len(list)) 运行结果: 另外考虑到有时候手抖多敲了空格

python学习—字符串

字符串拼接 s1="python" s2="hello" 1.+号 s3=s1+s2 2.join方法 obj.join() j=" " s4= j.join((s1,s2))  ---链接顺序:s1 j s2 字符串格式化输出 1.format name=input("输入名字:") a1="今天收到{},交来{},金额{}".format(name, "学费", 666) {:.3f

Python学习-字符串函数操作1

字符串的函数操作 capitalize():可以将字符串首字母变为大写 返回值:首字符大写后的新字符串 str = "liu" print(str.capitalize()); // Liu print(str); // liu lower():可以将字符串每个字符都变为小写 casefold():作用于lower() 相同,不同点是比它的功能更全面,可以将一些未知的变为小写 返回值:全部变为小写后的新字符串 str = "LIU" print(str.lower(

Python学习-字符串函数操作2

字符串函数操作 find( sub, start=None, end=None):从左到右开始查找目标子序列,找到了结束查找返回下标值,没找到返回 -1 sub:需要查找的字符串 start=None:开始查找的起始位置,默认起始的位置为可以省略(0) end=None:结束查找的位置,可以省略,默认为字符串的总长度len(str) str = 'liiuwen' m = str.find('i') n = str.find('i',4); print(m); // 1 print(n); //

Python学习-字符串函数操作3

字符串函数操作 isprintable():判断一个字符串中所有字符是否都是可打印字符的. 与isspace()函数很相似 如果字符串中的所有字符都是可打印的字符或字符串为空返回 True,否则返回 False str1 = 'gheruiv'; str2 = '\n\t'; print(str1.isprintable()); //True print(str2.isprintable()); //False istitle():判断一个字符串中所有单词的首字母是不是大写 返回值为布尔类型,T

Python学习-字符串的基本知识

字符串的基本知识 根据所展示形式的不同,字符串也可以分为两类 原始字符串: 使用单引号包括:'liuwen' 使用双引号包括:"liuwen" 使用3个单引号包括 :'''liuwen''' 使用3个双引号包括:"""liuwen""" 非原始字符串:就是在原始字符串的基础是左侧添加一个字母r 字符串中的有趣操作 如果将一个字符串相加会得到什么结果?相乘会得到什么结果? str = "liu" + &quo

python学习笔记2—python文件类型、变量、数值、字符串、元组、列表、字典

python学习笔记2--python文件类型.变量.数值.字符串.元组.列表.字典 一.Python文件类型 1.源代码 python源代码文件以.py为扩展名,由pyton程序解释,不需要编译 [[email protected] day01]# vim 1.py #!/usr/bin/python        print 'hello world!' [[email protected] day01]# python 1.py hello world! 2.字节代码 Python源码文件