Python基础语法四(字符串的索引、切片和内建方法)

索引

用于取某个字符

字符串str用[]下标进行索引,索引取出来的字符是新开辟的内存空间内的新的字符串

s = 'Python is the best program languge!'
s1 = [0]  # P
s2 = [3]  # t
s3 = [-1]  # !,下标[-1]表示倒数第一个

切片

用于截取子字符串,顾首不顾尾

str[[start]:[end:step]]
# 默认start=0,end=结尾的后一个字符,step=1
str = 'Python is the best program language'
str[:]  # 表示从头取到尾
str[0:3]  # 截取第一个到第三个字符,Pyt
str[:6:2]  # 从头到尾,间隔一个字符截取,Pto
str[-1:-5:-1]  # 倒着截取必须指定步长,egaug

猜你喜欢

转载自www.cnblogs.com/pyonwu/p/10469811.html