python—字符串切片

python—字符串切片

语法:字符串[开始索引:结束索:步长]

练习:

  1. 截取从2-5位置的字符串
def demo():
    s = "0123456789"
    print(s[2:6])       # 2345

2.截取2-末尾的字符串

def demo():
    s = "0123456789"
    print(s[2:])       # 23456789

3.截取从开始位置-5位置的字符串

def demo():
    s = "0123456789"
    print(s[:6])       # 012345

4.截取完整的字符串

def demo():
    s = "0123456789"
    print(s[:])       # 0123456789

5.从开始位置-7的位置,每隔一个字符截取字符串(这里为什么是2呢,0-2中间隔了1,因为0-1是一步,1-2又是一步)

def demo():
    s = "0123456789"
    print(s[:8:2])       # 0246

6.从开始位置,每隔一个字符截取字符串

def demo():
    s = "0123456789"
    print(s[::2])       # 02468

7.从索引1开始,每隔一个取一个

def demo():
    s = "0123456789"
    print(s[1::2])       # 13579

8.截取从2~末尾的字符串

def demo():
    s = "0123456789"
    print(s[2:-1])       # 2345678

9.截取字符串末尾两个字符串

def demo():
    s = "0123456789"
    print(s[-2:])       # 89

10.字符串的逆序(面试题)

def demo():
    s = "0123456789"
    print(s[-1::-1])       # 9876543210

你可能感兴趣的:(python,python)