deftrim(s):iflen(s) ==0:returnselse:whilelen(s) >0:ifs[0] =='': s= s[1:]elifs[-1] =='': s= s[:-1]elifs[0] !=''ands[-1] !='':breakreturns#测试:iftrim('hello') !='hello':print('测试失败!')eliftrim('hello') !='hello':print('测试失败!')eliftrim('hello')...
1.传入一个参数,判断该参数的长度是否为0,如果是,直接返回该参数; 2.如果长度不为0,循环判断该参数的首部是否有空格,如果有空格,去掉空格,再判断字符串的长度是否为0,如果是,直接返回字符串 3.还要循环判断该参数的尾部是否有空格,如果有空格,去掉空格,再判断字符串的长度是否为0,如果是,直接返回字符串 4.返...
def trim(s): #定义一个trim函数 if 0==len(s): return s #判断字符长度是否为0,如果是,直接返回字符串 while ''==s(0): #判断字符串首部是否有空格 s=s[1:] #如果有去掉空格 if 0==len(s): return s # 判断字符长度是否为0,如果是,直接返回字符串 while ''==s[-1]: #判断字符串尾部是...
^(\s+) 表示匹配以空格开头的字符串 (\s+)$ 表示匹配以空格结尾的字符串 | 表示或的意思 附录:Amoyshmily (霍格沃兹-百里) 2021 年6 月 10 日 04:26 3 解法1:分别找到首位非空格的元素的下标,然后切片 def trim1(string): cursor_l = 0 cursor_r = 0 for i in range(len(string)): if stri...
[廖雪峰python教程切片练习题]利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法。 题目链接: https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431756919644a792ee4ead724ef7afab3f7f771b04f5000...
= ' ': return s elif s[:1] == ' ': return trim(s[1:]) else: return trim(s[:-1]) 如果输入的字符串中,一边有空格的话,我还可以理解代码是如何工作的,但是如果字符串两边都有空格的话,我就不懂为什么会最后输出的时候两边的空格都没了。比如s = ' hello ',请问这个代码在输出的时候是...
你的测试代码没写好,所以搞不清具体哪个用例失败。建议 为每个测试用例定义不同的失败信息 用assert代替if else,像这样 assert trim(' hello') == 'hello'assert trim(' hello') != 'wrong'
deftrim(s): iflen(s)==0: return'' ifs[:1]==' ': returntrim(s[1:]) elifs[-1:]=='': returntrim(s[:-1]) else: returns # 测试: iftrim('hello ') !='hello': print('测试失败!') eliftrim(' hello') !='hello':
用切片操作,实现一个trim()函数,去除字符串首尾的空格。 s = 'hello ' def trim(s): return s if trim(s[0]) == ' ': print(s[1:]) elif trim(s[-1]) == ' ': print(s[:-1]) else: print('格式正确')
def trim(s): k = 0 '''while循环判断输入字符串是否为空值''' while k < len(s): if s[k] == ' ': #如果是空字符则记录字符的个数 k = k + 1 #k自增来记录数值 else: #否则字符串中遇到非空格 break #跳出循环 ''' 对字符数组进行输出 ''' if k == len(s): #如果全为空字符,...