【发布时间】:2019-10-05 21:36:57
【问题描述】:
我正在尝试创建一个函数来检查代码的每一行,并在每行的井号处和之后切断所有内容(如果存在),否则它将保持不变。我正在尝试返回相同的文本,但每一行都在井号处被截断。
问题是,当我打印文本时,我看到了结果,但是当我返回它时,什么也没有发生。
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
【问题讨论】:
-
你只能从一个函数返回一次,所以你可能不想在for循环中这样做。
-
@jonrsharpe 谢谢我将返回移出循环但现在我只看到一行。我做错了什么?
标签: python string loops replace split