【问题标题】:How can I execute my code using only one print statement?如何仅使用一个打印语句来执行我的代码?
【发布时间】:2022-01-05 11:15:25
【问题描述】:

所以我必须在假设分级器定义以下变量的同时编写代码

a to be some int
b to be some float
s to be some string

然后我必须编写一个程序,打印出以下内容,其中 中的值被变量内的实际值替换。但是,您只能使用 ONE print 语句。

// The variable 'a' has value of <a>. //
\\ While the variable 'b' has value of <b>. \\
// Lastly, the variable 's' has value of "<s>". //

例如,如果 a=1、b=1.5 和 s='hi',那么预期的输出是:

// The variable 'a' has value of 1. //
\\ While the variable 'b' has value of 1.5. \\
// Lastly, the variable 's' has value of "hi". //

这是我到目前为止所拥有的,这显然不起作用......

a = int
b = folat
s = str
print(f"// The variable 'a' has value of <{a}> . //\n \\ While the variable 'b' has value of <{b}> . \\ \\n// Lastly, the variable 's' has value of <{s}>. //")

我应该做些什么改变??

【问题讨论】:

标签: python list printing tuples


【解决方案1】:

您可以将 int 和 float 转换为字符串,然后在 print 语句中将它们全部连接起来。您还需要将\ 字符加倍,因为它是转义字符,并与进行字符一起充当单个字符:

a = 1
b = 1.0
s = "a"
print("// The variable 'a' has value of " + str(a) + ". //\n\\\\ While the variable 'b' has value of " + str(b) + ". \\\\ \n// Lastly, the variable 's' has value of " + s + ". //")

输出:

// The variable 'a' has value of 1. //
\\ While the variable 'b' has value of 1.0. \\
// Lastly, the variable 's' has value of a. //

【讨论】:

    【解决方案2】:

    考虑在 python 中使用多行打印功能。您还需要转义\,因为它本身就是一个转义字符,例如\n 是换行符,而不是字面上打印\n。并且通过\\ 意味着只是\

    a = 1
    b = 1.5
    s = "hi"
    
    print(
    f"""// The variable 'a' has value of {a}. //
    \\\\ While the variable 'b' has value of {b}. \\\\
    // Lastly, the variable 's' has value of "{s}". //"""
    )
    

    我个人认为这是最容易阅读和清理的,因为它看起来更像是所需的输出。

    【讨论】:

    • 这里唯一缺少的是使用{s!r} 而不是{s},以匹配预期的输出。但请注意,假设 OP 可以很好地使用单引号包裹的值 - 对于 dbl 引号,最好手动包裹它,例如 "{s}"
    • 感谢您的回复,但是如果 a、b 和 c 不是恒定的,这是否可行,例如如果 a、b 和 c 不同,我可以修改代码吗?如果更改 a、b 和 c 而不修改输入中的 a、b 和 c,代码将起作用?
    • @jordanparker 在这种情况下,您有几个不同的选择来处理它。最简单的方法可能是将print 包装在一个函数中,因此a,b,s 成为局部变量和函数的输入;或者您可以使用常规字符串并使用 str.format 在每次调用时替换为 var 的值。
    • @rv.kvtech 你说得对。我错过了必须引用字符串输入
    • @jordan 请原谅我,我不太明白你在问什么。你能澄清一下吗?也许为您的问题添加编辑
    猜你喜欢
    • 1970-01-01
    • 2022-10-23
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多