所以我有一个运行良好的项目,唯一的问题是我在文件内写入的返回值。这是我的代码:
def write_substrings_to_file(s,filename):
if type(s) != str:
raise TypeError ("You have entered something other than a sting, please enter a string next time!")
if s=="" or filename=="":
raise ValueError
why=open(filename,"wt")
output=""
if len(s)==1:
return s[0]
for i in range(0,len(s)):
for n in range(0,len(s)):
output+=s[i:n+1]
break
return output+write_substrings_to_file(s[1:],filename)
why.write()
why.close()
换句话说,我需要最后三行要
return output+write_substrings_to_file(s[1:],filename)
why.write(return)
why.close()
但是我无法以这种方式使用返回,我会收到以下错误
typeError:不能连接'str'和'type'对象
我不明白您在功能中要完成的工作,所以这可能不是您想要的,但是您的问题是您正在尝试写出return
,这是一个函数,当我认为您想编写递归堆积的字符串时,然后返回:
my_ret = output+write_substrings_to_file(s[1:],filename)
why.write(my_ret)
why.close()
return my_ret
感谢您解释问题,这是我要使用的代码:
def my_write(s, ind = 0, step = 1):
ret = []
if ind+step <= len(s):
ret.append(s[ind:ind+step])
step += 1
else:
step = 1
ind += 1
if ind < len(s):
ret += my_write(s,ind,step)
return ret
ret = my_write('abc')
print ret #<- outputs ['a', 'ab', 'abc', 'b', 'bc', 'c']
和代码高尔夫:
def break_word(s):
ret = [s[:x] for x in range(1,len(s)+1)]
ret += break_word(s[1:]) if len(s) > 1 else []
return ret
ret = break_word('abc')
print ret #<- outputs ['a', 'ab', 'abc', 'b', 'bc', 'c']