注册 登录
编程论坛 Python论坛

关于list里面数据问题

fcpplo 发布于 2019-10-24 21:24, 1440 次点击
请看以下代码:
def trim(s):
  if s[:1] == ' ':
        return trim(s[1:])
    elif s[-1:]==' ':
        return trim(s[:-1])
 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('测试成功!'
这个代码运行 最终显示‘测试成功‘


那么问题来了,
trim('')
函数里面
 if s[:1] == ' ':
        return trim(s[1:])
    elif s[-1:]==' ':
        return trim(s[:-1])

对于trim(''),s[:1]=='',s[1:2]=='' 我在Python里面用 bool(s[:1]==''),bool([1:2]==''),显示的值都是true 那这个函数为什么不是无限循环呢?
对于s=''   为什么s[0:1],s[1:2],s[2:3]....等等都是''

无法理解上述两个问题


2 回复
#2
fall_bernana2019-10-25 09:25
以下是引用fcpplo在2019-10-24 21:24:06的发言:

请看以下代码:
def trim(s):
  if s[:1] == ' ':
        return trim(s[1:])
    elif s[-1:]==' ':
        return trim(s[:-1])
 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('测试成功!'
这个代码运行 最终显示‘测试成功‘


那么问题来了,
trim('')
函数里面
 if s[:1] == ' ':
        return trim(s[1:])
    elif s[-1:]==' ':
        return trim(s[:-1])

对于trim(''),s[:1]=='',s[1:2]=='' 我在Python里面用 bool(s[:1]==''),bool([1:2]==''),显示的值都是true 那这个函数为什么不是无限循环呢?
对于s=''   为什么s[0:1],s[1:2],s[2:3]....等等都是''

无法理解上述两个问题

1. bool(s[:1]=='')你这个比对的是空. def trim(s):  if s[:1] == ' ': 这里比对的是空格. 所以你trim('') 直接是  return s
2. 对于字符串的切片操作,如果start和end之间没有和step方向一致元素间隔,会返回空切片,所以''切出的所有切片都是空.
#3
fcpplo2019-10-25 14:16
多谢大神指点
1