【问题标题】:Is there a way I can print multiple lines using one print()?有没有一种方法可以使用一个 print() 打印多行?
【发布时间】:2022-06-11 11:35:19
【问题描述】:

我是编程新手,无法理解 Python。我想只使用一个print() 来减少它的使用。

first_name = "Gabh"
Gabh ="Musician"
age = 21
height = 5.4
weight = 47
print(first_name + (" is a"), Gabh)
print(("age:"), age)
print(("height:"), height)
print(("weight:"), weight)

有了这段代码,我得到了:

Gabh is a Musician
age: 21
height: 5.4
weight: 47

【问题讨论】:

    标签: python


    【解决方案1】:

    使用单个 print() 语句,所有项目用逗号分隔。

    print(first_name, "is a", Gabh, "age:", age, "height:", height, "weight:", weight)
    

    【讨论】:

    • 要添加到约翰的答案,您可以插入带有特殊字符串的换行符:“\n”。这将有助于获得 4 行打印语句,而不是 1 大行。
    • 谢谢:D 我添加了 "\n" 以使它们在输出中保持相同的格式。
    【解决方案2】:

    如果您想打印一个预配置的多行文本块,只需向其中添加一些值(有点像在 Word 中进行邮件合并),您可以使用 str.format 方法。

    >>> help(str.format)
    
    format(...)
     |      S.format(*args, **kwargs) -> str
     |
     |      Return a formatted version of S, using substitutions from args and kwargs.
     |      The substitutions are identified by braces ('{' and '}').
    

    多行字符串有"""(或者,不太常见的是''')。

    template = """{name} is a {role}.
    Age: {age} 
    Height: {height} metres
    Weight: {weight} milligrams"""
    
    gabh = template.format(
        name="Gabh",
        role="Musician",
        age=21,
        height=5.4,
        weight=47
    )
    
    print(gabh)
    

    (这与 f-strings 略有不同,后者在创建字符串时将值放入字符串中。)

    如果您的字典的键与模板字符串中的{stuff} in {curly braces} 匹配,则可以使用format_map

    template = """{name} is a {role}.
    Age: {age} 
    Height: {height} metres
    Weight: {weight} milligrams"""
    
    gabh = {
        "name": "Gabh",
        "role": "Musician",
        "age": 21,
        "height": 5.4,
        "weight": 47,
    }
    
    print(template.format_map(gabh))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2010-09-17
      相关资源
      最近更新 更多