Python调用Proj05Runner模块run方法输出格式异常如何修复
代码修改方案
你的问题根源是字符串拼接逻辑错误,每一句版权声明后都拼接了原字符串、子串和截取结果,才导致内容穿插。调整拼接顺序,先完整拼接4行版权声明,再追加业务数据即可,修改后的模块代码如下:
def run(str, subStr): """Returns a substring of any given string based upon a given range of characters before and after the substring""" str_range = 3 if subStr in str: str_modified = str[str.index(subStr) - str_range : str.index(subStr) + len(subStr) + str_range] # 先拼接完整4行版权声明 copyright_content = ( "I certify that this program is my own work\n" "and is not the work of others. I agree not\n" "to share my solution with others.\n" "Print your name here." ) # 版权声明后拼接业务数据 return f"{copyright_content}\n\n{str}\n{subStr}\n{str_modified}" else: return "ERROR: subStr not found in str!"
修改后运行驱动代码,输出会先展示4行完整的版权声明,再空一行依次输出原字符串、子串、截取结果,符合需求。
内容的提问来源于stack exchange,提问作者MMx15
相关产品推荐
相关产品推荐

