You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拆分Python中的print语句实现多行打印输出?

解决方案:拆分print语句实现逐行输出

当然可以拆分,原代码的问题在于把重复后的元组直接传给print,导致所有内容挤在一行。下面提供两种简单的实现方式:

方法1:使用循环逐次打印

先构造好完整的输出字符串,再通过循环重复打印指定次数,每次print会自动换行:

your_name = input("Please tell me your name:  ")
your_age = int(input("Please tell me your age:  "))
print_times = int(input("How many times would you like to print this message? "))
years_old = 2023 + 100 - your_age

# 构造完整的消息字符串
message = f"Hi {your_name}, you will be 100 years old in {years_old}"
# 循环打印指定次数,每次一行
for _ in range(print_times):
    print(message)

方法2:用换行符拼接后一次性打印

如果不想用循环,可以把重复的消息用换行符\n连接成一个大字符串,再一次性打印:

your_name = input("Please tell me your name:  ")
your_age = int(input("Please tell me your age:  "))
print_times = int(input("How many times would you like to print this message? "))
years_old = 2023 + 100 - your_age

message = f"Hi {your_name}, you will be 100 years old in {years_old}"
# 用换行符重复拼接消息,再打印
print('\n'.join([message] * print_times))

额外说明:原代码用元组拼接的方式会让输出带有逗号和空格,改用f-string能让消息格式更整洁自然。

内容的提问来源于stack exchange,提问作者Lori Ann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:22:36