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

如何将Python中for循环的打印输出内容转换存储为单个变量

实现方案

精简版(无需numpy依赖)

word = input("Enter a word : ").strip()
# 生成带缩进的单行内容
indented_line = "    " + " ".join(word)
# 拼接5行内容为完整字符串赋值给e
e = "\n".join([indented_line for _ in range(5)])

# 测试输出
print(e)

兼容原有代码逻辑版本

import numpy as np
word = input("Enter a word : ")
pxlength = len(word)
word = " ".join(word)
m = np.str_(word)
# 给每行加缩进后拼接为完整字符串
e = "\n".join([f"    {m}" for _ in range(5)])

print(e)

原理解释

  • 你需要的行首缩进直接通过在每行内容前拼接4个空格" "实现
  • 用\n作为分隔符把5行带缩进的内容拼接成一个完整的字符串赋值给变量e,后续直接执行print(e)就能输出符合要求的格式
  • 如果你输入内容为Eitan,执行后print(e)的输出完全符合你给出的带缩进的示例效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:06:11