【Python 3.6.1】字符串截取
1:字符串索引
1 2 3 4 5 |
# 打印字符串 >>> s = 'HelloWorld' >>> print (s) HelloWorld >>> |
我们来数一下字符串的顺序号
1 2 |
HelloWorld 0123456789 |
通过上面的排序我们可以很清楚的看到每个字母的序号值
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> s = 'HelloWorld' >>> print (s[0]) H >>> print (s[1]) e >>> print (s[2]) l >>> print (s[3]) l >>> print (s[4]) o >>> |
2:字符串负索引(通过上面的测试,负索引也就好理解了)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
## 因为负整数是从-1开始,所以,第一个索引标号是-1 >>> s = 'HelloWorld' >>> print (s[-1]) d >>> print (s[-2]) l >>> print (s[-3]) r >>> print (s[-4]) o >>> print (s[-5]) W >>> |
3:分片
string[a:b] ,意思是截取字符串,从a开始到b,大于等于起始值,小于最大值( >=a and <b)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
>>> s = 'HelloWorld!' ## [0:5],比较好理解,<=0 and <5 >>> s[0:5] 'Hello' >>> ## [5:10],同上 >>> s[5:10] 'World' >>> ## [-6:-1],-6,从后往前数第6个字符开始,到-1的前面 >>> s[-6:-1] 'World' >>> ## 先截取[5:11],得到的结果再截取[-1] >>> s[5:11][-1] '!' >>> ## 如果分片的末尾数字远远大于字符串的长度,那么将返回从开始位置到字符串结尾的部分 >>> s[5:10000000] 'World!' >>> ## 如果分片的位置不在字符串所涉及的范围,那么不返回任何字符 >>> s[100000000:100] '' >>> |
4:空分片索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
>>> print (s[:5]) Hello >>> ## 等价于 >>> print (s[0:5]) Hello >>> >>> print (s[5:]) World! >>> ## 等价于 >>> print (s[5:11]) World! >>> >>> s[-6:] 'World!' >>> |