python初学的问题记录3-4


问题三

切片操作的注意事项,要防止空字符串引发的IndexError: list index out of range。

从例1可以看到对于非空字符串的切片操作,输出都是一样的,原因是slice不会改变原数据的数据形式,依然为str类型。

L= 'abc'
print(L[-1])
print(L[-1:])
print(L[0])
print(L[0:1])
 
#输出
#c
#c
#a
#a

  

但是如果L是空字符串,会报错。

L = ''
print(L[-1]) #报错
print(L[-1:]) #可以正常执行
print(L[0]) #报错
print(L[:1]) #可以正常执行
 
#输出
 
#print(L[-1])
#IndexError: string index out of range
#print(L[0])
#IndexError: string index out of range

  

由此可以看到有冒号和没有冒号的区别,尤其是在写自定义函数时,要写上冒号。

#自定义一个strip()函数
 
def trim(s):
    while s[:1] == ' ': # 如果是s[0]则会报错,因为编译器会认为s有为空字符的可能
        s = s[1:]
    while s[-1:] == ' ': # 如果是s[-1]则会报错,因为编译器会认为s有为空字符的可能
        s = s[:-2]
    return s
 
# 测试:
if trim('hello  ') != 'hello':
    print('测试失败!')
elif trim('  hello') != 'hello':
    print('测试失败!')
elif trim('  hello  ') != 'hello':
    print('测试失败!')
elif trim('  hello  world  ') != 'hello  world':
    print('测试失败!')
elif trim('') != '':
    print('测试失败!')
elif trim('    ') != '':
    print('测试失败!')
else:
    print('测试成功!')

  

问题四

从问题三拓展开,列表就不一样了,列表的下标问题,要注意区分slice和列表内容的类型区别。

如果是通过slice方式,那么生成的结果依然是个list,如果是下标取值,那么取到的是列表中的内容。

list1=['a', 'b', 3]
print(list1[0])
print(list1[:1])
print(list1[-1])
print(list1[-1:])
 
输出结果
#a
#['a']
#3
#[3]

  


原文:https://blog.csdn.net/handsomehuo/article/details/90299476

猜你喜欢

转载自www.cnblogs.com/qbdj/p/10901223.html
3-4