如何在单个打印语句中打印多行文本?

How would I print multiple lines of text in a single print statement?

想法是这样的:

a = input("insert name: ")
a
print("hi ", a, "!")
print("hello", a, "!")
print("good morning", a, "!")

但我需要知道是否有一种方法可以将所有内容打印成一个独特的东西,但包装文本有点像这样:print("hi ", a, "!" wrap "hello", a, "!" wrap "good morning", a, "!")

提前联系

能不能只打印一条语句:

print(f"hi {}! hello {a}! good morning {a}!")

您正在寻找换行符,'\n':

print("hi ", a, "!\n", "hello", a, "!\n", "good morning", a, "!")

当然,您可以使用各种字符串格式,例如 f 字符串、str.formatprintf 格式。

默认情况下,打印命令执行换行操作。但是您可以将该换行符更改为其他内容:

a = input("insert name: ")
a
print("hi ", a, "!", end=" ")
print("hello", a, "!", end=" ")
print("good morning", a, "!", end="\n")

我们可以在生成器中将字符串拆分成块来制作一个列表,我们可以用换行符将其加入

n = 5

wrapped = '\n'.join([string[i:i+n] for i in range(0,len(string),n)])

print(wrapped)

编辑:

抱歉误解了 'wrap' 的意思。

你可以做类似 print(sentence1, sentence2, … , sep="\n") 的事情,使用其他人为每个句子建议的 .format 方法。

我可以想到两个办法:

  • print("hi ", a, "!\n", "hello", a, "!\n", "good morning", a, "!") - 使用 \n 换行符 控制字符 (有关详细信息,请参阅 this question)。
  • 一个用于相同类型事物的生成器,但更容易,因为它为您插入 \n
def join(text):
  for i in range(len(text)):
    text[i] = [item if isinstance(item, str) else ''.join(item) for item in text[i]]
  lines = [' '.join(item) for item in text]
  return '\n'.join(lines)

# Usage:
print(join([[["hi ", a, "!"]], ["hello", [a, "!"]], ["good morning", a, "!"]]))

# Equal to:
print("hi " + a + "!")  # See how nested items (e.g [a, "!"] in ["hello", [a, "!"]]) represent simple concatenation (the equivalent of `+` in `print()`)
print("hello", a + "!")  # while sister items (e.g "good morning" and a in ["good morning", a, "!"]) represent joining with space (the equivalent of ',' in `print()`)
print("good morning", a, "!")

解释:

  1. 遍历并找到连接字符串的位置以及分隔字符串的位置。

    1a。 for i in range(len(text))::遍历数组,存储当前数组索引

    1b。 [item if isinstance(item, str) else ''.join(item) for item in text[i]]:让我们分解一下。我们获取当前项目 - 由 text[i] 表示(因为这是在 for 循环内,每个项目看起来像 ["hello", [a, "!"]]) - 并循环遍历它。因此,变量 item 的值将类似于 "hello"[a, "!"]。接下来,我们使用 isinstance 来检查该项目是否为字符串。如果是这样,我们就离开它。否则,它是一个数组,所以我们将其中的所有值连接在一起,没有分隔符。所以,完整的例子是:[[["hi ", "dog", "!"]], ["hello", ["dog", "!"]], ["good morning", "dog", "!"]] 变成 [["hi dog!"], ["hello", "dog!"], ["good morning", "dog", "!"]]

  2. lines = [' '.join(item) for item in text]:用 text 中的每个项目创建一个数组,一个嵌套数组,但使用 </code> 连接在一起。这导致将嵌套数组展平为基本的一维数组,每个单独的项目数组替换为由空格分隔的版本(例如 <code>[['hi', 'my', 'friend'], ['how', 'are', 'you']] 变为 ['hi my friend', 'how are you']

  3. '\n'.join(lines) 将平面数组中的每个字符串连接在一起,使用 \n 控制字符(参见上面的 link)作为分隔符(例如 ['hi my friend', 'how are you'] 变为 'hi my friend\nhow are you')

在 Python 中有很多方法可以做到这一点。这是一个使用 str class 的 .format(*args, **kwargs) 方法的方法:

print("hi, {0}!\nhello, {0}!\ngood morning, {0}!".format(a))

注意换行的 '\n' 字符。