Python中字符串切片详解

# str[索引:索引:步长]

num_str = "0123456789"

# 截取2-5位置的字符串

print(num_str[2:6])

# 输出结果:
2345

# 截取2到末尾的字符串

print(num_str[2:])

# 输出结果
23456789

# 截取从开始到5的字符串

print(num_str[:6])

# 输出结果
012345

# 截取完整的字符串

print(num_str[:])

# 输出结果

0123456789

# 从开始位置每隔一个字符截取一个字符串

print(num_str[::2])

# 输出结果
02468

# 从索引1位置每隔一个字符截取一个字符串

print(num_str[1::2])

# 输出结果
13579

# 截取从索引2到-1的字符串

print(num_str[2:-1])

# 输出结果
2345678

# 截取字符串末尾的两个字符串

print(num_str[-2:])

# 输出结果:
89

# 字符串的逆序 面试题

print(num_str[-1::-1])
print(num_str[::-1])

# 输出结果
9876543210

 



posted @ 2018-12-06 11:04  皮皮虾的海绵宝宝  阅读(7102)  评论(0编辑  收藏  举报