通过Python示例了解切片符号

使用切片符号的语法

    object[begin:end]   # 从begin开始,在end-1结束
    object[end:]        # 从开始开始,其余的项目
    object[:stop]       # 从0开始,在第1结束处停止
    object[:]           # 返回整个数组的副本
    object[begin:end:step]  # 从begin开始,在end-1结束 with given step

理解切片符号的Python程序

x = [10, 20, 30, 40, 50] # list
y = (10, 20, 30, 40, 50) # 元组
z = "https://www.nhooo.com/" # 字符串

print("x =", x)
print("y =", y)
print("z =", z)print()print("x[0:5] =", x[0:5])
print("x[0:4] =", x[0:4])
print("x[2:5] =", x[2:5])
print("x[0:] =", x[0:])
print("x[:5] =", x[:5])
print("x[:3] =", x[:3])
print("x[0:5:2] =", x[0:5:2])print()print("y[0:5] =", y[0:5])
print("y[0:4] =", y[0:4])
print("y[2:5] =", y[2:5])
print("y[0:] =", y[0:])
print("y[:5] =", y[:5])
print("y[:3] =", y[:3])
print("y[0:5:2] =", y[0:5:2])print()print("z[0:5] =", z[0:5])
print("z[0:4] =", z[0:4])
print("z[2:5] =", z[2:5])
print("z[0:] =", z[0:])
print("z[:5] =", z[:5])
print("z[:3] =", z[:3])
print("z[0:5:2] =", z[0:5:2])print()

输出结果

x = [10, 20, 30, 40, 50]
y = (10, 20, 30, 40, 50)
z = https://www.nhooo.com/

x[0:5] = [10, 20, 30, 40, 50]
x[0:4] = [10, 20, 30, 40]
x[2:5] = [30, 40, 50]
x[0:] = [10, 20, 30, 40, 50]
x[:5] = [10, 20, 30, 40, 50]
x[:3] = [10, 20, 30]
x[0:5:2] = [10, 30, 50]

y[0:5] = (10, 20, 30, 40, 50)
y[0:4] = (10, 20, 30, 40)
y[2:5] = (30, 40, 50)
y[0:] = (10, 20, 30, 40, 50)
y[:5] = (10, 20, 30, 40, 50)
y[:3] = (10, 20, 30)
y[0:5:2] = (10, 30, 50)

z[0:5] = https
z[0:4] = http
z[2:5] = tps
z[0:] = https://www.nhooo.com/
z[:5] = https
z[:3] = htt
z[0:5:2] = hts