Discuss / Python / 多种实现方式

多种实现方式

Topic source

恢弘腾达

#1 Created at ... [Delete] [Delete and Lock User]
# 方式一:递归
def trim(s):
    if s[:1] == ' ':
        return trim(s[1:])
    if s[-1:-2:-1] == ' ':
        return trim(s[:-1])
    return s

# 方式二:查找起始位置
def trim(s):
    b = 0
    e = len(s)
    for i in range(e):
        if s[i] != ' ':
            break
        b += 1
    for i in range(e)[::-1]:
        if s[i] != ' ':
            break
        e = i
    return s[b:e]

# 方式三:查找起始位置
def trim(s):
    while s and s[0] == ' ':
        s = s[1:]
    while s and s[-1] == ' ':
        s = s[:-1]
    return s

请问第三种方法里面while语句为什么要加上 s and 呢?

恢弘腾达

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

while语句的判断条件中加上s,是为了排除s为空字符串的情况。

因为s为空时,对变量s进行切片时,会报错“索引错误”。

你可以去掉后试试下面的代码。

trim('')

感谢,打开了我的思路~


  • 1

Reply