首页 > 解决方案 > 从函数返回多条数据的问题

问题描述

我正在尝试创建一个函数来检查代码的每一行,并在每行的井号处和之后切断所有内容(如果存在),否则它将保持不变。我正在尝试返回相同的文本,但每一行都在井号处被截断。

问题是,当我打印文本时,我看到了结果,但是当我返回它时,什么也没有发生。

code_1='''
hello this is a test to remove anything after
 and to get #this letter out 
 def hello_world():        # this is a comment
    print("Hello world!") # this is another comment
print("I # like # pound sign # .")
'''

def remove_octothorpe_and_after(code):
    code_in_lines = code.splitlines()
    for i in code_in_lines:
        if '#' in i:
            index=i.index('#')
            aftertext=i[index:]
            i = i.replace(aftertext,"")
        new_code=("".join(i))
        return new_code

标签: pythonstringloopsreplacesplit

解决方案


退货不是那样工作的。相反,请使用列表:

def foo():
    bar = []
    for x: 
        bar.append(y)
    return bar

print(foo())

或转换为生成器:

def baz():
    for x:
        yield y

foobar = baz()

for result in foobar:
    print(result)

推荐阅读