Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 如何使用;返回值“;以书面形式_Python 2.7_File_Return - Fatal编程技术网

Python 2.7 如何使用;返回值“;以书面形式

Python 2.7 如何使用;返回值“;以书面形式,python-2.7,file,return,Python 2.7,File,Return,所以我有一个运行良好的项目,唯一的问题是我得到的返回值要写在一个文件中。这是我的密码: 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 Value

所以我有一个运行良好的项目,唯一的问题是我得到的返回值要写在一个文件中。这是我的密码:

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()
但是我不能以这种方式使用return,我得到以下错误

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 my_write(s,ind=0,step=1):
ret=[]

如果ind+step你能解释这个函数应该做什么吗?让我们假设输入是“abc”打开一个文件,写以下内容:a ab abc b bc c另一个解释,输入:great g gr grea grea grea rea rea ea eat a at t,然后保存该文件,另一件事是递归函数
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']