Discuss / Python / 打卡,作业

打卡,作业

Topic source

人玉匆花

#1 Created at ... [Delete] [Delete and Lock User]

切片方法:

def trim(s):

    while s[:1] == ' ':

        s = s[1:]

    while s[-1:] == ' ':

        s = s[:-1]

    return s

**PS:**1.当字符串不为空时用[:1]、切片第一个元素,用[-1:]切片最后一个元素。2.索引不能为空,切片可以为空。也就是

a = [1]

a[1]  # 报错

a[1:]  # 值为空的切片

递归方法:

def trim(s):

    if s[:1] == ' ':

        return trim(s[1:])

    elif s[-1:] == ' ':

        return trim(s[:-1])

    return s

**PS:**没有定义递归出口,而是定义了递归入口,或者说定义了递归出口是没有满足递归条件的S切片


  • 1

Reply