1、切片(slice)


练习
利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
#trim()
def trim(s):
print('s=[%s]'%s)
if len(s)==0:
return s
b=0
e=-1
while len(s)>0 and s[b]==' ':
s=s[b+1:]
print(s)
while len(s)>0 and s[e]==' ':
s=s[:e]
print(s,'\n')
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('测试成功!')
本文介绍了一个使用Python切片操作实现的自定义trim函数,该函数能够去除字符串两端的空格,不依赖于内置的strip方法。通过实际代码示例,展示了如何逐步检查并移除字符串开头和结尾的空白字符。
527

被折叠的 条评论
为什么被折叠?



