Discuss / Python / 数组和字符串切片的结果并不一样

数组和字符串切片的结果并不一样

Topic source

Nil_大黄

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

对if判断条件这里没有想明白, 看来字符串切片后的结果是字符, 而数组切片还是数组

然而字符串也可以像数组一样用下标操作

def trim(s):    if s[:1] == ' ':        return trim(s[1:])    elif s[-1:] == ' ':        return trim(s[:-1])    else:        return sL = [' ', 'Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']print(L[0] == ' ') # TRUEprint(L[:1] == ' ') # FALSE

S = ' Hello'
print(S[0] == ' ') # TRUE
print(S[:1] == ' ') # TRUE

Nil_大黄

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

代码格式整理

def trim(s):    if s[:1] == ' ':        return trim(s[1:])    elif s[-1:] == ' ':        return trim(s[:-1])    else:        return sL = [' ', 'Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']print(L[0] == ' ')print(L[:1] == ' ')S = ' Hello'print(S[0] == ' ')print(S[:1] == ' ')

  • 1

Reply