【问题标题】:How would I print multiple lines of text in a single print statement? [closed]如何在单个打印语句中打印多行文本? [关闭]
【发布时间】:2019-08-11 14:31:32
【问题描述】:

这个想法是这样的:

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

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

提前打个招呼

【问题讨论】:

    标签: python string line


    【解决方案1】:

    我可以想到两种方法:

    • 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 中的每个项目创建一个数组,这是一个嵌套数组,但使用 连接在一起。这导致将嵌套数组展平为基本的一维数组,每个单独的项目数组替换为由空格分隔的版本(例如,[['hi', 'my', 'friend'], ['how', 'are', 'you']] 变为 ['hi my friend', 'how are you']

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

    【讨论】:

      【解决方案2】:

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

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

      注意'\n' 字符换行。

      【讨论】:

        【解决方案3】:

        你能用一个语句打印出来吗:

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

        【讨论】:

          【解决方案4】:

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

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

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

          【讨论】:

          • 亲爱的投票者,请解释这个答案有什么问题,以便我改进它
          【解决方案5】:

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

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

          【讨论】:

            【解决方案6】:

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

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

            编辑:

            抱歉误解了 'wrap' 的含义。

            您可以使用其他人为每个句子建议的.format 方法来执行print(sentence1, sentence2, … , sep="\n") 之类的操作。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多