python字符串中一般都会存在多个字符,如何进行截取呢
例如:name = ‘my name is jockey’
我们首先对这个字符串进行编号,从0开始:
1.打印某个字符
>>> print(name[0])
m
>>> print(name[11])
j
2.打印其中一段字符
如果冒号一侧为空标识该侧取到底,取值的时候遵循左闭右开原则,即:[ )
>>> print(name[3:14])
name is joc
>>> print(name[6:])
e is jockey
>>> print(name[:16])
my name is jocke
>>> print(name[:17])
my name is jockey
3.反向截取
反向截取时从右往左排序的时候是从-1开始而不是从0开始
成段打印时还是左闭右开,与正向保持一致
>>> print(name[-1])
y
>>> print(name[-6])
j
>>> print(name[-9:-1])
is jocke
借鉴别处看来的一个有趣的练习:
“找出你朋友中的魔鬼”
word = 'friends'
find_the_evil_in_your_friends = word[0] + word[2:4] + word[-3:-1]
print(find_the_evil_in_your_friends)
执行结果为:fiend 魔鬼