python - 从函数返回多条数据的问题
问题描述
我正在尝试创建一个函数来检查代码的每一行,并在每行的井号处和之后切断所有内容(如果存在),否则它将保持不变。我正在尝试返回相同的文本,但每一行都在井号处被截断。
问题是,当我打印文本时,我看到了结果,但是当我返回它时,什么也没有发生。
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
解决方案
退货不是那样工作的。相反,请使用列表:
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)
推荐阅读
- css - 如何使用自定义字体更改 Bootstrap 表单输入的字体样式
- java - 如何在 Pattern.compile("\\R").splitAsStream(input) 中包含尾随空字符串?
- javascript - 工作箱服务人员在除 Chrome 之外的任何地方工作:未捕获(承诺)DOMException
- scala - 是否收到询问模式覆盖消息
- laravel-5 - 是否有任何包或东西可以与 laravel-5.0 一起使用,将视频从我的 laravel 视图上传到单个 youtube 频道
- angular - 如何防止 mat-select 在值选择时跳转到选定值?
- html - 如何更改悬停框中的图像
- rxjs - rxjs:组合两个流,但在第二个发送事件后取消第一个
- php - 如何在 PHP Codeigniter 中修复日期格式
- asterisk - 如何使用 PJSIP 在 Asterisk 上转发 sip 呼叫?