如何将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
相关产品推荐
相关产品推荐

