如何让Python函数返回的列表输出时各元素分行显示?
问题描述
现有童谣列表如下:
nursery_rhyme = [ 'This is the house that Jack built.', 'This is the malt that lay in the house that Jack built.', 'This is the rat that ate the malt that lay in the house that Jack built.', 'This is the cat that killed the rat that ate the malt that lay in the house that Jack built.' ]
用于返回指定范围诗句的recite函数实现如下:
def recite(start_verse, end_verse): lines = [] start = start_verse lines.append(nursery_rhyme[(start-1)]) while start < end_verse: start += 1 line = nursery_rhyme[start-1] lines.append(line) return (lines)
调用示例:
print(recite(1,2))
当前输出格式为:
['This is the house that Jack built.', 'This is the malt that lay in the house that Jack built.']
需要将输出调整为如下格式化样式:
[ 'This is the house that Jack built.', 'This is the malt that lay in the house that Jack built.' ]
解决方法
方法1:使用pprint模块(推荐)
Python内置的pprint模块专门用于美化打印数据结构,默认会生成带换行和缩进的输出:
from pprint import pprint pprint(recite(1,2))
执行后即可直接得到目标格式的输出。
方法2:手动拼接格式化字符串
如果不想引入额外模块,可以手动构建输出字符串,精准控制格式:
result = recite(1,2) output = "[\n" for idx, line in enumerate(result): # 最后一行不加逗号 suffix = ",\n" if idx != len(result)-1 else "\n" output += f" '{line}'{suffix}" output += "]" print(output)
方法3:利用json.dumps调整格式
通过json模块的dumps方法,设置indent参数实现换行缩进:
import json result = recite(1,2) print(json.dumps(result, indent=1))
注意:该方法会将字符串的单引号转换为双引号,如果对引号类型有严格要求,此方法需额外处理。
内容的提问来源于stack exchange,提问作者Wakayamba
相关产品推荐
相关产品推荐

